基于内容的动态 UITableView 单元格高度 [英] Dynamic UITableView Cell Height Based on Contents

查看:34
本文介绍了基于内容的动态 UITableView 单元格高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用自定义单元格填充的 UITableView(继承自 UITableViewCell),每个单元格包含一个 UIWebView,它会根据自动调整大小在它的内容上.事情就是这样,我如何根据内容(变量 webView)更改 UITableView 单元格的高度.

I have a UITableView that is populated with custom cells (inherited from UITableViewCell), each cell contains a UIWebView that is automatically resize based on it's contents. Here's the thing, how can I change the height of the UITableView cells based on their content (variable webView).

解决方案必须是动态的,因为用于填充 UIWebViews 的 HTML 是从不断变化的提要中解析出来的.

The solution must be dynamic since the HTML used to populate the UIWebViews is parsed from an ever changing feed.

我觉得我需要使用 UITableView 委托方法 heightForRowAtIndexPath 但从它的定义来看:

I have a feeling I need to use the UITableView delegate method heightForRowAtIndexPath but from it's definition:

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ;//This needs to be variable
}

我无法访问单元格或其内容.我可以在 cellForRowAtIndexPath 中更改单元格的高度吗?

I can't access the cell or it's contents. Can I change the height of the cell in cellForRowAtIndexPath?

任何帮助都会很棒.谢谢.

Any help would be grand. Thanks.

我在 2 年前问过这个问题.随着自动布局的介绍,可以找到 iOS7 的最佳解决方案:

I asked this question over 2 years ago. With the intro of auto layout the best solution for iOS7 can be found:

在 UITableView 中使用自动布局进行动态单元格布局 &可变行高

在 iOS8 上,此功能内置于 SDK

and on iOS8 this functionality is built in the SDK

推荐答案

我发现的动态高度的最佳方法是预先计算高度并将其存储在某种集合(可能是数组)中.假设单元格主要包含文本,可以使用-[NSString sizeWithFont:constrainedToSize:lineBreakMode:] 计算高度,然后在heightForRowAtIndexPath:

The best way that I've found for dynamic height is to calculate the height beforehand and store it in a collection of some sort (probably an array.) Assuming the cell contains mostly text, you can use -[NSString sizeWithFont:constrainedToSize:lineBreakMode:] to calculate the height, and then return the corresponding value in heightForRowAtIndexPath:

如果内容不断变化,您可以实现一种在提供新数据时更新高度数组的方法.

If the content is constantly changing, you could implement a method that updated the array of heights when new data was provided.

这篇关于基于内容的动态 UITableView 单元格高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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