1.WKWebView自适应布局加载完成后停留的位置不在顶部,总有些距离,解决方法:
在- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation方法中执行:
[webView evaluateJavaScript:@"window.scrollTo(0,0)" completionHandler:nil];
注意:如果在这个didFinishNavigation方法中还执行了别的操作,可能上面这句代码没有效果。那么延迟一会再执行就好了。
如:
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再执行刷新
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监听实现的。
首先:注册监听
[self.webView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
其次 KVO回调:
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
//更具内容的高重置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;
}