iOS中精确计算WebView高度的方法示例

2020-01-21 05:50:12刘景俊

#pragma mark ----- webView 的 delegate 
- (void)webViewDidFinishLoad:(UIWebView *)webView 
{ 
//获取页面高度(像素) 
NSString * clientheight_str = [webView stringByEvaluatingJavaScriptFromString: @"document.body.offsetHeight"]; 
float clientheight = [clientheight_str floatValue]; 
//设置到WebView上 
webView.frame = CGRectMake(15, _whereNewsLabel.bottom+10, f_Device_w-30, clientheight); 

//下面这样写就是获取到比较准确的内容高度,不需要再进行其他计算了 
//获取内容实际高度(像素) 
NSString * height_str= [webView stringByEvaluatingJavaScriptFromString: @"document.getElementById('webview_content_wrapper').offsetHeight + parseInt(window.getComputedStyle(document.getElementsByTagName('body')[0]).getPropertyValue('margin-top')) + parseInt(window.getComputedStyle(document.getElementsByTagName('body')[0]).getPropertyValue('margin-bottom'))"]; 
float height = [height_str floatValue]; 

//再次设置WebView高度(点) 
webView.frame = CGRectMake(15, _whereNewsLabel.bottom+10, f_Device_w-30, height); 

if ([self.delegate respondsToSelector:@selector(backWebViewWithHeight:)]) { 
[self.delegate backWebViewWithHeight:webView.bottom+5]; 
} 
} 

有写代码是我项目中使用的,没有必要用,大家可以根据自己的需要修改,必要的代码上面都有

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对ASPKU的支持。


注:相关教程知识阅读请移步到IOS开发频道。