UITableViewCell无法使用systemLayoutSizeFittingSize获得正确的宽度

时间:2014-12-01 05:23:57

标签: ios uitableview autolayout

我使用autolayout + xib构建单元格,单元格的高度是动态的,所以我使用systemLayoutSizeFittingSize来获取

的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;

我的代码是这样的:

enter image description here 这将打印这样的日志: enter image description here

所以我们可以发现,从systemLayoutSizeFittingSize返回的大小可能比我的设备屏幕(iPhone5:320点)更宽,这怎么可能发生? (我尝试添加layoutIfNeededupdateConstraintsIfNeeded,但问题仍然存在。

我正在使用Xcode 6,其中xib文件大小未修复。

PS:我的视图包含一个多行标签,我打印了这个标签的preferredMaxLayoutWidth,我发现preferredMaxLayoutWidth也很大,可能是这个问题。但是如何解决呢?

1 个答案:

答案 0 :(得分:2)

是的,这是错误的preferredMaxLayoutWidth的问题,通过在自定义单元格的updateConstraints中添加此行来修复     self.contentLabel.preferredMaxLayoutWidth = CGRectGetWidth(self.contentLabel.frame);

PS

实际上,我发现在调用单元格的layoutSubview之后,单元格的子视图可能无法获得正确的宽度,因此如果要根据标签的宽度设置preferredMaxLayoutWidth,则最好在layoutIfNeeded中设置preferredMaxLayoutWidth而不是layoutSubViews