加載Html代碼
WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]]];
[self.view addSubview:webView];
加載的狀態(tài)回調(diào) (WKNavigationDelegate)
// 頁(yè)面開(kāi)始加載時(shí)調(diào)用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation;
// 當(dāng)內(nèi)容開(kāi)始返回時(shí)調(diào)用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation;
// 頁(yè)面加載完成之后調(diào)用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation;
// 頁(yè)面加載失敗時(shí)調(diào)用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation;
WKWebView圖片自適應(yīng) 超過(guò)屏幕寬的自適應(yīng)玩郊,小于屏幕寬度的圖片不放大
- (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調(diào)用js方法
//禁用webview長(zhǎng)按(提高用戶體驗(yàn))
[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"]
WKWebView調(diào)用js方法 (替換方法)
[webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none';" completionHandler:nil];
[webView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none';" completionHandler:nil];