如何在可变高度 UITableView 内根据内容确定 UIWebView 高度? [英] How to determine UIWebView height based on content, within a variable height UITableView?

查看:27
本文介绍了如何在可变高度 UITableView 内根据内容确定 UIWebView 高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个具有可变高度行的 UITableView,如 这个问题

I am trying to create a UITableView with variable height rows as explained in the answer to this question

我的问题是每个单元格都包含一个具有不同(静态加载)内容的 UIWebView 我不知道如何根据内容计算适当的高度.有没有办法做到这一点?我试过这样的事情:

My problem is each cell contains a UIWebView with different (statically loaded) content I can't figure out how to calculate the proper height based on the content. Is there a way to do this? I've tried things like this:

   (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
       WebViewCell *cell = (WebViewCell*)[self tableView:tableView cellForRowAtIndexPath:indexPath];
       [cell setNeedsLayout];
       [cell layoutIfNeeded];
       return cell.bounds.size.height;
    }

单元格本身是从笔尖加载的,笔尖只是一个包含 UIWebViewUITableViewCell.(如果单元格只是将自己调整为最大的 html 内容也可以,尽管可变高度会更好).

The cells themselves are loaded from a nib, which is simply a UITableViewCell containing a UIWebView. (It would also be fine if the cells just adjusted themselves to the largest of the html content, though variable height would be nicer).

推荐答案

这段代码对于表格视图的使用来说可能太慢了,但确实有效.看起来没有其他选择,因为 UIWebView 不提供对 DOM 的直接访问.

This code is probably too slow for table view use, but does the trick. It doesn't look like there's any alternative, as UIWebView offers no direct access to the DOM.

在视图控制器的 viewDidLoad 中,我在 webview 中加载一些 HTML,加载完成后运行一些 javascript 以返回元素高度.

In a view controller's viewDidLoad I load some HTML in a webview and when the load is finished run some javascript to return the element height.

- (void)viewDidLoad
{
    [super viewDidLoad];
    webview.delegate = self;
    [webview loadHTMLString:@"<div id='foo' style='background: red'>The quick brown fox jumped over the lazy dog.</div>" baseURL:nil];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSString *output = [webview stringByEvaluatingJavaScriptFromString:@"document.getElementById("foo").offsetHeight;"];
    NSLog(@"height: %@", output);
}

这篇关于如何在可变高度 UITableView 内根据内容确定 UIWebView 高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆