美文网首页iOS Developer
WKWebView常用介绍

WKWebView常用介绍

作者: zhaok | 来源:发表于2017-03-03 11:21 被阅读108次

加载Html代码

WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]]];
[self.view addSubview:webView];

加载的状态回调 (WKNavigationDelegate)

// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation;
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation;
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation;
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation;

WKWebView图片自适应 超过屏幕宽的自适应,小于屏幕宽度的图片不放大

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
[webView evaluateJavaScript:[NSString stringWithFormat:@"var script = document.createElement('script');"
                                 "script.type = 'text/javascript';"
                                 "script.text = \"function ResizeImages() { "
                                 "var myimg,oldwidth;"
                                 "var maxwidth = %f;" //判断条件
                                 "for(i = 0;i < document.images.length;i++){"
                                 "myimg = document.images[i];"
                                 "if(myimg.width > maxwidth){" //小于或者大于
                                 "oldwidth = myimg.width;"
                                 "myimg.width = maxwidth;"
//                                 "myimg.height *= (maxwidth/oldwidth);" //图片高度
                                 "}"
                                 "}"
                                 "}\";"
                                 "document.getElementsByTagName('head')[0].appendChild(script);",screen_width-20] completionHandler:nil];
    
    [webView evaluateJavaScript:@"ResizeImages();" completionHandler:nil];
}

UIWebView调用js方法

//禁用webview长按(提高用户体验)
[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"]

WKWebView调用js方法 (替换方法)

[webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none';" completionHandler:nil];
[webView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none';" completionHandler:nil];

相关文章

网友评论

    本文标题:WKWebView常用介绍

    本文链接:https://www.haomeiwen.com/subject/jublgttx.html