- (void)viewDidLoad {
[self.webView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
}
- (void)dealloc {
[self.webView.scrollView removeObserver:self forKeyPath:@"contentSize" context:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
if (object == self.webView.scrollView && [keyPath isEqual:@"contentSize"]) {
// we are here because the contentSize of the WebView's scrollview changed.
UIScrollView *scrollView = self.webView.scrollView;
NSLog(@"New contentSize: %f x %f", scrollView.contentSize.width, scrollView.contentSize.height);
}
}
2017/7/14 更新:
碰到KVO无限触发可以用js方法获取高度
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
[webView evaluateJavaScript:@"Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight)"
completionHandler:^(id _Nullable result, NSError * _Nullable error) {
if (!error) {
NSNumber *height = result;
// do with the height
}
}];
}
网友评论
(lldb) po error
Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={NSLocalizedDescription=A JavaScript exception occurred}
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
__block CGFloat webViewHeight;
//获取内容实际高度(像素)
[webView evaluateJavaScript:@"document.body.offsetHeight" completionHandler:^(id _Nullable result,NSError * _Nullable error) {
//获取页面高度,并重置webview的frame
webViewHeight = [result doubleValue];
NSLog(@"%f",webViewHeight);
dispatch_async(dispatch_get_main_queue(), ^{
[self layoutWithWebHeight:webViewHeight];
});
}];
NSLog(@"结束加载");
}