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

查看:138
本文介绍了基于内容的动态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是从不断变化的Feed中解析的。

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:

http:// t.co/PdUywcTjhu

在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天全站免登陆