如何设置UITableViewCell的高度 [英] How does the height of a UITableViewCell get set
问题描述
我知道当UIKit呈现一个单元格时,它使用 tableView:heightForRowAtIndexPath:
来计算高度。我的问题是,如何以及何时在实际的 UITableViewCell
上设置。我想构建动态单元格,并且需要计算单元格中文本的位置。我相信我可以使用self.bounds和self.frame - 我只是好奇它们设置的位置 - 即使使用 dequeueReusableCellWithIdentifier
。
I know that when UIKit renders a cell, it uses tableView:heightForRowAtIndexPath:
to calculate the height. My question is, how and when does that get set on the actual UITableViewCell
. I want to build dynamic cells and will need to calculate the placement of text within the cell. I believe I can just use self.bounds and self.frame - I was just curious about at what point those are set - even with the use of dequeueReusableCellWithIdentifier
.
谢谢。
推荐答案
从返回单元格后tableView:cellForRowAtIndexPath:
,tableview设置了许多属性,包括单元格的边界,然后调用 tableView:willDisplayCell:forRowAtIndexPath:
。该调用之后的唯一修改是设置alpha / frame,即使那时只有动画行。
After you return the cell from tableView:cellForRowAtIndexPath:
, the tableview sets a number of properties, including the bounds of the cell, then calls tableView:willDisplayCell:forRowAtIndexPath:
. The only modifications after that call are setting alpha/frame, and even then only when animating the row.
鉴于此,如果您使用的是股票 UITableViewCell
,您可以在 tableView:willDisplayCell:forRowAtIndexPath:
中布局文本,并确保单元格已经具有正确的宽度/高度。也就是说,如果您正在做的不仅仅是基础知识,您可能需要考虑继承 UITableViewCell
。在您的子类中,您可以在 layoutSubviews
中布置字段,并确保您的单元格始终正确布局。
Given that, if you're using a stock UITableViewCell
, you can layout your text in tableView:willDisplayCell:forRowAtIndexPath:
and be assured that the cell already has the correct width/height. That said, if you're doing anything more than just the basics, you may want to consider subclassing UITableViewCell
. In your subclass, you can lay out your fields in layoutSubviews
and be assured that your cell will always be laid out correctly.
这篇关于如何设置UITableViewCell的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!