关于UIWebView设置高度自适应的问题

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 66, 320, 480)];
    
    //中间还有其他控件
    
//创建webView时要设置一个临时的frame,不然的话webViewDidFinishLoad代理方法中设置webView高度自适应之后,webView会有很多空白 _webView
= [[UIWebView alloc]initWithFrame:CGRectMake(0, 100, 320, 10)]; _webView.delegate = self; //_webView.ScalesPageToFit = YES;//可以用捏合手势来放大或缩小webView页面 _webView.scrollView.scrollEnabled = NO;//禁止UIWebView滚动 //WebView加载本地的html数据 NSMutableDictionary *dict = [LoadFileTools loadWebViewContentsWithFileName:kJobDescribe]; NSString *filePath = [dict objectForKey:@"filePath"]; NSString *htmlString = [dict objectForKey:@"htmlString"]; [_webView loadHTMLString:htmlString baseURL:[NSURL URLWithString:filePath]]; } - (void)webViewDidFinishLoad:(UIWebView *)webView {

   //获取WebView内容的高度(貌似这两种方式都行)
   //NSString *contentH = [webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"];
   NSString *contentH = [webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"];

    //计算坐标
    CGFloat webViewY = otherControlY + 50;
    CGFloat webViewH = [contentH floatValue] + 25;
    
    webView.frame = CGRectMake(12, webViewY, 320 - 12, webViewH);
    //禁止选中
    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
    //禁止弹出菜单
    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];
    
    //设置滚动区域
    _scrollView.contentSize = CGSizeMake(0, webViewY + webViewH - 10);
    [_scrollView addSubview:_webView];
    [self.view addSubview:_scrollView];
}
原文地址:https://www.cnblogs.com/hw140430/p/4179494.html