iOS UIWebView 获取内容实际高度,关闭滚动效果

这几天改需求,要求将 UIWebView 嵌套在 UIScrollView 里,由 UISCrollView 控制滚动,需要使 UIWebView 的高度同内容高度一致,网上搜索的到代码:

CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];

这段代码是没有效果的,body 获取到的 offsetHeight,为显示区域的高度,因此修改如下:

首先遵守协议并设置代理:

self.myWebView.delegate = self;

self.headerView.frame = CGRectMake(0, 0, 375, 150);

self.myScrollView.frame = CGRectMake(0, 0, 375, 667);

在代理方法 - (void)webViewDidFinishLoad:(UIWebView *)webView 中获取高度:

CGFloat height = [[self.myWebView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];

改变 webView 的高度

self.myWebView.frame = CGRectMake(0, 150, 375, height);

关闭 webView 的滚动

UIScrollView *tempView = (UIScrollView *)[self.myWebView.subviews objectAtIndex:0];

tempView.scrollEnabled = NO;

改变 ScorllView 的高度

self.myScrollView.contentSize = CGSizeMake(375, height + self.headerView.frame.size.height);

搞定.

你可能感兴趣的:(iOS UIWebView 获取内容实际高度,关闭滚动效果)