如何使用自动布局时就知道了的UITableViewCell的宽度是多少?

问题描述:

我有一个的UITableViewCell 这里我把它内容查看标签和使用自动布局其他的事情。我加了限制,其中之一是,该内容查看具有比相同的边界在的UITableViewCell

I have an UITableViewCell where I put in its contentView labels and other things using the auto layout. I added constraints, one of them being that the contentView has the same bounds than the UITableViewCell.

(在故事板,为方便起见,我选择了 iphone 4英寸作为的大小模拟指标

(On the storyboard, for convenience, I selected iphone 4-inch as the size of the simulated metrics.)

添加约束后,我称之为 layoutIfNeeded ,因为我需要让我的单元格的大小。约束确实奠定了,因为我可以看到我的内容查看是现在的的UITableViewCell 大小相同。问题是,在的UITableViewCell 尚未适应屏幕尺寸的大小,但(我想这是因为我的细胞都很好稍后自动完成)。所以,我还是对的iphone 4寸大小,而我在iPhone上4.7英寸。

After adding the constraints, I call layoutIfNeeded as I need to get the size of my cells. The constraints are indeed laid out as I can see that my contentView is now the same size of the UITableViewCell. The problem is that the size of the UITableViewCell hasn't been adapted to the size of the screen yet (I guess it's done automatically later as my cells are fine). So I'm still on the size of an iphone 4 inches while I am on an iphone 4.7 inches.

有没有触发我的细胞的最终大小像有办法迫使布局使用方法 layoutIfNeed

Is there a way to trigger the final size of my cells like there is a way to force lay out using layoutIfNeed?

在加载从故事板或笔尖的细胞,它在笔尖不是最后一个指定的大小。在的cellForRowAtIndexPath添加您的意见和约束的内容查看,然后调整宽度做cell.width = tableView.width。最后,调用layoutIfNeeded因为你之前这样做。

When you load the cell from storyboard or nib, it has the specified size in the nib not the final one. In cellForRowAtIndexPath add your views and constraint to the contentView, then adjust the width doing cell.width = tableView.width. Finally, call layoutIfNeeded as you were doing it before.

这将导致与细胞的正确宽度的完整的布局。

That will cause a complete layout with the correct width of the cell.

编辑:这工作,因为即使寿要装入与自动布局(translatesAutoresizingMasksIntoConstraints = NO)笔尖启用,每个笔尖文件的第一个视图始终自动布局禁用(translatesAutoresizingMasksIntoConstraints = YES)

This works because even tho you are loading the nib with autolayout enabled (translatesAutoresizingMasksIntoConstraints = NO), the first view of every nib file has always autolayout disabled (translatesAutoresizingMasksIntoConstraints = YES).

这意味着,渲染视图(这样做layoutIfNedded)的时候,自动布局会​​考虑实际的框架和口罩属性来确定正确的尺寸。

This means that when rendering the view (so doing layoutIfNedded), autolayout will consider the actual frame and masks property to determine the correct size.