iOS UIWebView根据web内容大小实时刷新webView高度

项目中有时候会遇到这样的情况 需要禁止webView内部滑动 让webView本身跟着父视图一起滑动,这样就需要确定webView的高度,但是iOS端提前是不知道h5内容高度的 这就需要我们实时根据web内容刷新webView的高度


#解决方案

1.创建webView时候需要先禁止webView滑动

1
_footerView.scrollView.scrollEnabled = NO;

####2.使用KVO监听webViewcontentSize

1
[_footerView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];

####3.实现监听方法

1
2
3
4
5
6
7
8
9
10
11
12
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"contentSize"]) {
CGFloat webViewHeight = [[_footerView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
//获取内容高度后 更新webView高度
CGRect newFrame = _footerView.frame;
newFrame.size.height = webViewHeight;
_footerView.frame = newFrame;
[_tabelView reloadData];
}
}

document.body.offsetHeightdocument.body.scrollHeightdocument.body.clientHeight三个似乎是一个意思 但有时候个别不管用 可以都试试 滑稽!

全部代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
_footerView= [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, kScreen_width, 100)];
_footerView.delegate = self;
_footerView.scrollView.scrollEnabled = NO;
[_footerView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:MyGradeH5Url]]];
[_footerView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
//
_tabelView.tableFooterView = _footerView;
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"contentSize"]) {
CGFloat webViewHeight = [[_footerView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
CGRect newFrame = _footerView.frame;
newFrame.size.height = webViewHeight;
_footerView.frame = newFrame;
[_tabelView reloadData];
}
}