您的位置:首页 > 移动开发

UIWebView自适应高度,适合一个页面多个WebView

2016-05-26 17:50 423 查看
先给加载的html字符串添加一个div

NSString * htmlcontent = [NSString stringWithFormat:@"<div id=\"webview_content_wrapper\">%@</div>", tiaojian];


在- (void)webViewDidFinishLoad:(UIWebView *)webView的代理方法中写如下代码:

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
// 整体缩放,改变文字大小(可不加)
[webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust='78%'"];
// 改变文字颜色(可不加)
[webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= 'gray'"];
//获取页面高度(像素)
NSString * clientheight_str = [webView stringByEvaluatingJavaScriptFromString: @"document.body.offsetHeight"];
float clientheight = [clientheight_str floatValue];
//设置到WebView上(此部分修改未自己的webView的frame)
webView.frame = CGRectMake(8, 0, kScreenWidth - 8, clientheight);
//获取WebView最佳尺寸(点)
CGSize frame = [webView sizeThatFits:webView.frame.size];
//获取内容实际高度(像素)
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的真实高度
height = height * frame.height / clientheight;
// 只需再次设置WebView高度(点), 即可.

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: