我们想要的结果是将 WebView 设置为不可滚动,与原生的 UI 融合在一起,那这种情况下,我们必须得到 WebView 的内容高度,让 WebView 的高度与它所需要加载的网页的内容高度一致,才能让 WebView 将内容完全显示。
开始我是在加载完成的回调中去获取 webView 的 contentSize的高度
- (void)webViewDidFinishLoad:(UIWebView *)webView{ webViewHeight=[webView.scrollView contentSize].height; CGRect newFrame = webView.frame; newFrame.size.height = webViewHeight; webView.frame = newFrame; mainTableView.sectionHeaderHeight = webViewHeight; [mainTableView setTableHeaderView:webView];}
用这样的方法得到高度很有可能不是web的真实高度,如果web中有很多 图片未加载完成 的话,获取的高度将小于真实高度,那在它加载完成后,内容将显示不全。
解决
最终我是监听了 webView的 contentSize,每当contentSize的值改变时就去更改webView 的frame。
[activityWebView.scrollView addObserver: self forKeyPath: @ "contentSize" options: NSKeyValueObservingOptionNew context: nil]; - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{ if ([keyPath isEqualToString:@"contentSize"]) { webViewHeight = [[activityWebView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue]; CGRect newFrame = activityWebView.frame; newFrame.size.height = webViewHeight; activityWebView.frame = newFrame; [mainTableView setTableHeaderView:activityWebView]; }}
在页面消失时记得 remove 监听对象,否则会闪退
-(void)viewWillDisappear:(BOOL)antimated{
[super viewWillDisappear:antimated];
[activityWebView.scrollView removeObserver:self
forKeyPath:@"contentSize" context:nil];
}