首页 > 移动平台 > 详细

iOS WebView自适应高度

时间:2015-10-13 16:50:58      阅读:420      评论:0      收藏:0      [点我收藏+]
//
  _webView = [[UIWebView alloc] initWithFrame: CGRectMake(0, 0, self.view.frame.size.width, 0)];
  _webView.delegate = self;
  _webView.scrollView.bounces = NO;
  _webView.scrollView.showsHorizontalScrollIndicator = NO;
  _webView.scrollView.scrollEnabled = NO;
  [_webView sizeToFit];

  ///////////////////////////////设置内容,这里包装一层div,用来获取内容实际高度(像素),htmlcontent是html格式的字符串//////////////	
  NSString * htmlcontent = [NSString stringWithFormat:@"<div id=\"webview_content_wrapper\">%@</div>", htmlcontent];
  [_webView loadHTMLString:htmlcontent baseURL:nil];

  ////////////////////////////////delegate的方法重载////////////////////////////////////////////
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
  //获取页面高度(像素)
  NSString * clientheight_str = [webView stringByEvaluatingJavaScriptFromString: @"document.body.offsetHeight"];
  float clientheight = [clientheight_str floatValue];
  //设置到WebView上
  webView.frame = CGRectMake(0, 0, self.view.frame.size.width, 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];
  //内容实际高度(像素)* 点和像素的比
  height = height * frame.height / clientheight;
  //再次设置WebView高度(点)
  webView.frame = CGRectMake(0, 0, self.view.frame.size.width, height);
}

 以上Copy自http://www.cnblogs.com/be-bright/p/4485774.html,仅用作自己用

iOS端webView setScalesPageToFit:YES完美解决。Android客户端注入js解决。//暂时没做测试

iOS WebView自适应高度

原文:http://www.cnblogs.com/FGGblog/p/4874656.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!