ios UIWebView 获取高度

WebView内容高度的问题,相信很多人都遇到过,无法获取到准确高度,导致页面布局出现差错,下面一起学习下 获取高度的几种方法
1 、我们通过获取 webView的ScrollvIew的内容的高度来获取webView的高度

  CGFloat webViewHeight = [self.webView.scrollView contentSize].height;
  //获取网页现有的frame
  CGRect webViewRect = webView.frame;
  //修改webView的高度
  webViewRect.size.height = webViewHeight;
  webView.frame = webViewRect;

2、使用js 来获取网页的高度

NSString * jsString = @"document.body.offsetHeight";
CGFloat webViewHeight = [[webView stringByEvaluatingJavaScriptFromString:jsString] floatValue];
// 获取网页的frame
CGRect webViewRect = webView.frame;
//修改webView的高度
webViewRect.size.height = webViewHeight;
webView.frame = webViewRect;

3、通过监听实现

//监听webview
[self.webView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];

//监听触发

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context

{
    if ([keyPath isEqualToString:@"contentSize"]) {
        //通过webview的contentSize获取内容高度
        self.webViewHeight = [self.webView.scrollView contentSize].height;
        CGRect newFrame = self.webView.frame;
        newFrame.size.height = self.webViewHeight;
        NSLog(@"-webViewHeight-----%f",self.webViewHeight);
    }
}

//移除观察者

-(void)dealloc
{
    [self.webView.scrollView removeObserver:self forKeyPath:@"contentSize" context:nil];
}

以上三个方法可以实现webView的高度问题,第三个方法最佳

demo 下载

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值