方法一:js調(diào)用
//頁面加載完成之后調(diào)用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
WS(weakSelf);
[webView evaluateJavaScript:@"document.body.offsetHeight;" completionHandler:^(id _Nullable any, NSError * _Nullable error) {
NSString *heightStr = [NSString stringWithFormat:@"%@",any];
weakSelf.webHeight = heightStr.floatValue;
}
注:有時webview無論是JS獲取婆硬,還是contentSize獲取,最后結(jié)果都難以獲取到準(zhǔn)確高度奸例,并非方法不行彬犯,而是,webViewDidFinishLoad代理方法被調(diào)用時查吊,頁面并不一定完全展現(xiàn)完成谐区,可能有圖片還未加載出來,導(dǎo)致此時獲取的高度是偏小的逻卖,過會兒圖片加載出來后宋列,瀏覽器會重新排版網(wǎng)頁被撐大,而我們之前給的高度不夠內(nèi)容的展示评也,導(dǎo)致顯示異常炼杖。
方法二:kvo
給webView的scrollView的contentSize屬性添加監(jiān)聽,每當(dāng)內(nèi)容發(fā)生變化盗迟,contentSize一定會跟著變坤邪,捕獲這個變動。
[self.webView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
if ([keyPath isEqualToString:@"contentSize"]) {
CGSize fittingSize = [self.webView sizeThatFits:CGSizeZero];
NSLog(@"-------%@",NSStringFromCGSize(fittingSize));
}
}