一、頭文件添加<JavaScriptCore/JavaScriptCore.h>,定義webView窗口以及創(chuàng)建JSContext 對(duì)象,添加UIWebViewDelegate代理
#import <JavaScriptCore/JavaScriptCore.h>
@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong)JSContext *context;
二、創(chuàng)建webView
-(void)SVGShow{
self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
[self.view addSubview:self.webView];
//設(shè)置屬性
self.webView.delegate = self;
self.webView.scalesPageToFit = YES;
self.webView.multipleTouchEnabled = YES;
self.webView.userInteractionEnabled = YES;
self.webView.scrollView.scrollEnabled = YES;
//可網(wǎng)絡(luò)加載SVG圖
NSString *svgPath = [[NSBundle mainBundle] pathForResource:@"文件名稱" ofType:@"svg"];
NSData *svgData = [NSData dataWithContentsOfFile:svgPath];
NSString *reasourcePath = [[NSBundle mainBundle] resourcePath];
NSURL *baseUrl = [[NSURL alloc] initFileURLWithPath:reasourcePath isDirectory:true];
[_webView loadData:svgData MIMEType:@"image/svg+xml" textEncodingName:@"UTF-8" baseURL:baseUrl];
//iOS11廢棄了automaticallyAdjustsScrollViewInsets屬性,需要使用scrollview的contentInsetAdjustmentBehavior屬性
if (@available(iOS 11.0, *)) {
self.webView.scrollView.contentInsetAdjustmentBehavior= UIScrollViewContentInsetAdjustmentNever;
} else {
// Fallback on earlier versions
}
}
三、實(shí)現(xiàn)代理
#pragma - mark WebViewDelegate 必須都實(shí)現(xiàn),否則會(huì)有警告
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
return YES;
}
//這個(gè)代理必須實(shí)現(xiàn),否則將無法注入JS
- (void)webViewDidStartLoad:(UIWebView *)webView{
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
self.context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
self.context[@"對(duì)應(yīng)的網(wǎng)頁調(diào)用方法"] = ^(返回的參數(shù)) {
};
}
JS與OC交互可參考http://www.itdecent.cn/p/6d399be6cb87