iOS WKWebView高度自適應以及截獲頁面點選的url
首先來看下UIWebView的做法:
UIWebView *webView = [[UIWebViewalloc]initWithFrame:CGRectMake(0,0,WIDTH,0)];
webView.delegate =self;
[self.viewaddSubview:webView];
[webView loadHTMLString:html/*html內容*/ baseURL:nil];
-(void)webViewDidFinishLoad:(UIWebView*) webView {
//獲取頁面高度,並重置webview的frame
CGFloat documentHeight = [[webView
CGRect frame = webView.frame;
frame.size.height = documentHeight;
webView.frame = frame;
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType
NSString* strRequest = request.URL.absoluteString;
if([strRequestisEqualToString:@"about:blank"]) {//主頁面載入內容
returnYES;//允許跳轉
} else {//截獲頁面裡面的連結點選
//do something you want
returnNO;//不允許跳轉
}
}
在來對應看下WKWebView:
WKWebView *wkWebview = [[WKWebView
wkWebview.navigationDelegate = self;
[self.view wkWebview];
[wkWebview loadHTMLString:html/*html內容*/ baseURL:nil];
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecifiedWKNavigation *)navigation {
[webView evaluateJavaScript:@"document.getElementById(\"content\").offsetHeight;"completionHandler:^(id_Nullableresult,NSError *_Nullable error) {
//獲取頁面高度,並重置webview的frame
CGFloat documentHeight = [resultdoubleValue];
CGRect frame = webView.frame;
frame.size.height = documentHeight;
webView.frame = frame;
}];
}
// 類似 UIWebView的 -webView: shouldStartLoadWithRequest: navigationType:
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction*)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
NSString *strRequest = [navigationAction.request.URL.absoluteStringstringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
if([strRequestisEqualToString:@"about:blank"]) {//主頁面載入內容
decisionHandler(WKNavigationActionPolicyAllow);//允許跳轉
} else {//截獲頁面裡面的連結點選
//do something you want
decisionHandler(WKNavigationActionPolicyCancel);//不允許跳轉
}
}
高度自適應程式碼下載連結:http://download.csdn.net/detail/luco2008/9502733