• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Manager_Xiao
博客园    首页    新随笔    联系   管理    订阅  订阅

iOS WebView自适应高度

//
  _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解决。//暂时没做测试

posted @ 2015-10-13 15:03  Manager_Xiao  阅读(187)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3