這幾天改需求由捎,要求將 UIWebView 嵌套在 UIScrollView 里,由 UISCrollView 控制滾動燕刻,需要使 UIWebView 的高度同內(nèi)容高度一致只泼,網(wǎng)上搜索的到代碼:
CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
這段代碼是沒有效果的,body 獲取到的 offsetHeight卵洗,為顯示區(qū)域的高度请唱,因此修改如下:
首先遵守協(xié)議并設(shè)置代理:
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);
關(guān)閉 webView 的滾動
UIScrollView *tempView = (UIScrollView *)[self.myWebView.subviews objectAtIndex:0];
tempView.scrollEnabled = NO;
改變 ScorllView 的高度
self.myScrollView.contentSize = CGSizeMake(375, height + self.headerView.frame.size.height);
搞定.