有没有更好的方法来确定UITableViewCell的正确大小? [英] Is there a better way to determine the right size for a UITableViewCell?

查看:107
本文介绍了有没有更好的方法来确定UITableViewCell的正确大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个UITableView单元格,将有一个可变的大小,取决于它的内容(潜在的几行文字)。

I have a UITableView cell that is going to have a variable size depending on it's content (potentially several lines of text).

SInce看起来在之前调用了heightForRowAtIndexPath单元格,我通过在我的文本上调用[NSString sizeWithFont]来猜测正确的高度串。有没有更好的方法来设置高度之后我已经在单元格中的文本,并有一个想法是什么大小应该是什么?

SInce it appears that heightForRowAtIndexPath is called before I layout the cell, I just guess the correct height by calling [NSString sizeWithFont] on my text string. Is there a better way to set the height after I've laid out the text in the cell and have an idea of exactly what size it should be?

推荐答案

它会听起来很蠢,但...呃......在退出heightForRowAtIndexPath之前布局你的单元格;)

It's going to sound dumb, but ...uh... "layout your cell before you exit heightForRowAtIndexPath" ;)

很明显,虽然 - 操作系统只有在需要的时候才调用这个函数(如:创建单元格并在屏幕上显示它),因此,准备显示并不浪费人力。

Seriously, though -- the OS only ever calls this if it's going to be needed (as in: it's about to create the cell & display it on screen), so laying it out & getting ready to display is not wasted effort.

请注意,您需要分开进行布局,逻辑方面。只需在您的heightForRowAtIndexPath例程中调用您的[self prepLayoutForCellAtIndex:index]。

Note, you do not have to do your layout separately, logic-wise. Just make a call to your [self prepLayoutForCellAtIndex:index] within your heightForRowAtIndexPath routine.

如果数据是静态的,您可以创建一个高度表并缓存信息。 / p>

If the data is static, you can create a height table and cache the info.

if (0 == heightTable[index]) {
    heightTable[index] = [self prepLayoutForCellAtIndex:index];
}
return (heightTable[index]);

即使数据更改,您也可以重新计算方法中的表值,数据,或清除为0,以便下次需要时重新计算。

Heck, even if the data changes, you can either recalculate the table value in the method that changes the data, or clear to 0 so it gets recalculated the next time it's needed.

这篇关于有没有更好的方法来确定UITableViewCell的正确大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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