項目中遇到這樣的問題:webview放在uiscrollview,webview加載本地html,以後須要計算webview高度。html
步驟以下:web
1.首先建立webview.幾點注意,高度必定要小於你要加載的html的高度,最好設定個最小值,好比1;而且設置scalesPageToFit = YES使之自適應高度;ui
self.bottomWebView = [[UIWebView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.middleView3.frame) + kSectionInterval, kScreenWidth, 100)]; self.bottomWebView.layer.borderColor = self.topView.layer.borderColor; self.bottomWebView.layer.borderWidth = self.topView.layer.borderWidth; self.bottomWebView.scalesPageToFit = YES;
2.其次在控制器中顯示。設置代理,加載h5lua
self.recordScrollView.bottomWebView.delegate = self; [self loadH5WithId:self.check.checkId]; [self.view addSubview:self.recordScrollView];
3.加載h5代理
NSString *path = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"cj%d.htm", (int)checkId + 1] ofType:nil]; NSString *htmlString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; NSURL *baseUrl = [NSURL fileURLWithPath:path]; [self.recordScrollView.bottomWebView loadHTMLString:htmlString baseURL:baseUrl];
4.代理方法中計算高度orm
- (void)webViewDidFinishLoad:(UIWebView *)webView{ float webViewHeight = [[webView stringByEvaluatingJavaScriptFromString: @"document.body.scrollHeight"] floatValue]; webView.frame = CGRectMake(CGRectGetMinX(webView.frame),CGRectGetMinY(webView.frame),CGRectGetWidth(webView.frame),webViewHeight); webView.scrollView.scrollEnabled = NO; float heightSum = CGRectGetMinY(webView.frame) + webViewHeight + 15;//15增量 self.recordScrollView.contentSize = CGSizeMake(kScreenWidth, heightSum); }
這樣就能夠自適應高度了。htm