之前項目需求一個view
上面是web下面是原生,如何算出web高度布局下面視圖view.y
。
eg:上面是新聞下面是評論,評論要用原生實現。
兩種方法,方法1可以得到內容的實際高度,方法2得到了將內容顯示完整后的 webView 的尺寸(包含 UIEdgeInsets)
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//方法1 實際使用js方法實現
CGFloat documentWidth = [[webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('content').offsetWidth"] floatValue];
CGFloat documentHeight = [[webView stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"content\").offsetHeight;"] floatValue];
NSLog(@"documentSize = {%f, %f}", documentWidth, documentHeight);
//方法2
CGRect frame = webView.frame;
frame.size.width = 768;
frame.size.height = 1;
// webView.scrollView.scrollEnabled = NO;
webView.frame = frame;
frame.size.height = webView.scrollView.contentSize.height;
NSLog(@"frame = %@", [NSValue valueWithCGRect:frame]);
webView.frame = frame;
}
如果獲取高度不準
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), queue, ^{
寫上面介紹的方法
});