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 下载

猜你喜欢

转载自blog.csdn.net/u013983033/article/details/83827566