4

我有一个UITableViewCell包含 aUIWebView作为子视图。Web 视图填充了整个单元格。我estimatedRowHeight用来计算行高。但是,在构建表格视图时,单元格没有高度,因为 web 视图没有加载它的内容,因此单元格没有内容。因此,estimatedRowHeight返回 44 而不是 Web 视图内容的正确高度。

有谁知道当内容没有立即设置时我如何正确计算行的高度?有没有办法在同一个表格视图中估计某些单元格的高度并明确设置其他单元格的高度?

这就是我的使用方式estimatedRowHeight

self.tableView.estimatedRowHeight = 200;
self.tableView.rowHeight = UITableViewAutomaticDimension;

我没有使用委托方法。我已经尝试过了,但它并没有改变结果。我正在使用的单元格有一个 xib,它也使用自动布局约束。需要明确的是,该单元格确实出现了,并且 Web 视图确实被添加到了该单元格中。问题是单元格的高度不足以显示整个 Web 视图。Web 视图为音频播放器加载 HTML 嵌入代码。

4

2 回答 2

13

我做了一些摆弄,发现您可以通过UITableViewAutomaticDimension以下方式使用:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TableSection *tableSection = (self.tableModel.sections)[indexPath.section];

    if (tableSection.sectionType == TableSectionTypeWebView)
    {
        return 120;
    }
    else
    {
        return UITableViewAutomaticDimension;
    }
}

这基本上是说,对任何 WebView 部分使用 120 的高度,但对于其他一切,我希望你弄清楚高度。我在这里使用我自己的自定义表格模型(即 TableSection、sectionType 等...)

我必须添加self.tableView.estimatedRowHeight = 200;到我的init方法中才能起作用。

现在我可以提供估计的行高,但也可以为某些部分显式设置行高,如果我愿意,甚至可以为某些行设置。

我还没有看到任何文档,但是我用可变长度的字符串对其进行了测试,它保持得很好。

于 2014-11-11T19:36:56.160 回答
0

您将您的课程设为 UIWebViewDelegate,然后将您的课程设置为 UITableViewCell 中每个 UIWebView 的委托

-(void)webViewDidFinishLoad:(UIWebView *)aWebView {
    CGRect frame = aWebView.frame;
    frame.size.height = 1;
    aWebView.frame = frame;
    //Asks the view to calculate and return the size that best fits //its subviews.
    CGSize fittingSize = [aWebView sizeThatFits:CGSizeZero];
    frame.size = fittingSize;
    aWebView.frame = frame;
    [self.tableView beginUpdates];
    [self.tableView  endUpdates];
}

现在您可以获取 UIWebView 的高度并将其设置为行高,因为一旦调用了“beginUpdates”,将再次调用以下方法

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:  (NSIndexPath*)indexPath {
    return _webView.frame.size.height;
}

希望这可以帮助

于 2014-11-11T17:43:51.677 回答