1.WKWebView自適應(yīng)布局加載完成后停留的位置不在頂部,總有些距離冕香,解決方法:
在- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation方法中執(zhí)行:
[webView evaluateJavaScript:@"window.scrollTo(0,0)" completionHandler:nil];
注意:如果在這個didFinishNavigation方法中還執(zhí)行了別的操作儒喊,可能上面這句代碼沒有效果镣奋。那么延遲一會再執(zhí)行就好了。
如:
NSString *injectionJSString = @"var script = document.createElement('meta');"
"script.name = 'viewport';"
"script.content=\"width=device-width, user-scalable=no\";"
"document.getElementsByTagName('head')[0].appendChild(script);";
[webView evaluateJavaScript:injectionJSString completionHandler:^(id _Nullable success, NSError * _Nullable error) {
NSLog(@"完成");
//延遲0.3s再執(zhí)行刷新
dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC));
dispatch_after(delayTime, dispatch_get_main_queue(), ^{
[webView evaluateJavaScript:@"window.scrollTo(0,0)" completionHandler:nil];
});
}];
2.WKWebView如何獲得加載完成后的寬高怀愧。
試了幾種方法效果都不好侨颈,最后用KVO監(jiān)聽實現(xiàn)的。
首先:注冊監(jiān)聽
[self.webView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
其次 KVO回調(diào):
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
//更具內(nèi)容的高重置webView視圖的高度
NSLog(@"Height is changed! height= %@", [change valueForKey:NSKeyValueChangeNewKey]);
CGSize size = self.webView.scrollView.contentSize;
NSLog(@"height = %f",size.height);
self.webContainViewHeight.constant = size.height;
}