UIWebView加载SVG图以及交互

一、头文件添加,定义webView窗口以及创建JSContext 对象,添加UIWebViewDelegate代理

#import 

@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong)JSContext *context;

二、创建webView

-(void)SVGShow{
    self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    [self.view addSubview:self.webView];
    //设置属性
    self.webView.delegate = self;
    self.webView.scalesPageToFit = YES;
    self.webView.multipleTouchEnabled = YES;
    self.webView.userInteractionEnabled = YES;
    self.webView.scrollView.scrollEnabled = YES;
   //可网络加载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
    }
}

三、实现代理

#pragma - mark WebViewDelegate  必须都实现,否则会有警告
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    return YES;
}
//这个代理必须实现,否则将无法注入JS
- (void)webViewDidStartLoad:(UIWebView *)webView{
    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    self.context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    self.context[@"对应的网页调用方法"] = ^(返回的参数) {
        
    };
}

JS与OC交互可参考https://www.jianshu.com/p/6d399be6cb87

你可能感兴趣的:(UIWebView加载SVG图以及交互)