计算 UIWebView 的内容高度

本文介绍如何使用 iOS 中的 UIWebView 实现网页内容加载完成后自动调整视图的高度,并提供了两种不同的实现方法及其代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. - (void)webViewDidFinishLoad:(UIWebView *)webView  
  2. {      
  3. NSString *height_str= [webView stringByEvaluatingJavaScriptFromString: @"document.body.offsetHeight"];  
  4.     int height = [height_str intValue];  
  5.     webView.frame = CGRectMake(0,0,320,height);  
  6.     NSLog(@"height: %@", [webView stringByEvaluatingJavaScriptFromString: @"document.body.offsetHeight"]);  
  7. }  

http://blog.youkuaiyun.com/matrixhero/article/details/8443972

http://segmentfault.com/q/1010000000180759

- (void)webViewDidFinishLoad:(UIWebView *)webView { //webview 自适应高度
    CGRect frame = webView.frame;
    CGSize fittingSize = [webView sizeThatFits:CGSizeZero];
    frame.size = fittingSize;
    webView.frame = frame; 
    //tableView reloadData
}

from: http://www.cnblogs.com/ihojin/p/webview-contentheight.html

先是 html 文件内容

复制代码
// index.html
<html>
<body>
    <div id="content" contenteditable="false" style="font-family: Helvetica">
        <a href="id:abc" style="text-decoration:none; color:green">
            John
        </a>
        : This is out Rich Text Editing View
    </div>
</body>
</html>
复制代码

加载 html 文件

复制代码
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    NSBundle *mainBundle = [NSBundle mainBundle];
    NSURL *indexFileURL = [mainBundle URLForResource:@"index" withExtension:@"html"];
    [self.webView loadRequest:[NSURLRequest requestWithURL:indexFileURL]];
}
复制代码

计算 webView 显示内容后实际高度

两种方法,方法1可以得到内容的实际高度,方法2得到了将内容显示完整后的 webView 的尺寸(包含 UIEdgeInsets)

复制代码
- (void)webViewDidFinishLoad:(UIWebView *)wb
{
    //方法1
    CGFloat documentWidth = [[wb stringByEvaluatingJavaScriptFromString:@"document.getElementById('content').offsetWidth"] floatValue];
    CGFloat documentHeight = [[wb stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"content\").offsetHeight;"] floatValue];
    NSLog(@"documentSize = {%f, %f}", documentWidth, documentHeight);
    
    //方法2
    CGRect frame = wb.frame;
    frame.size.width = 768;
    frame.size.height = 1;

//    wb.scrollView.scrollEnabled = NO;
    wb.frame = frame;
    
    frame.size.height = wb.scrollView.contentSize.height;
    
    NSLog(@"frame = %@", [NSValue valueWithCGRect:frame]);
    wb.frame = frame;
}
复制代码

截图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值