您可以尝试使用this method。它与您的问题 99% 相似。先尝试让它只对Label起作用,然后再添加其他的UIViews
这里有一些关于问题解决方案的想法。
我将从上面的链接中复制部分代码。
首先,我将讨论仅带有标签的简化表格单元格。在 Storyboard 中添加 4 个约束(尾随和前导、标签和父视图之间的顶部和底部间距)。
在这种情况下,单元格的高度应该如下:
内容视图高度 = 顶部约束 + 标签高度 + 底部
约束
- (void)configureCell:(CustomCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
cell.customLabel.text = self.tableData[indexPath.row];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomCell *cell = [self.tableView dequeueReusableCellWithReuseIdentifier:@"custom_cell"]
[self configureCell:cell atIndexPath:indexPath];
// here is HUGE mistake in link above! Be careful!
[cell setNeedsLayout];
[cell layoutIfNeeded];
CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
return height + 1;
}
下面是代码的作用:
1. Configuring the content of the cell
2. Forcing a layout of the cell to apply constraints
3. Getting the height of the contentView, computed using Auto-Layout. We can’t directly call systemLayoutSizeFittingSize:UILayoutFittingCompressedSize: on the cell because the constraints we’ve set up are relative to the content view. Finally, we use UILayoutFittingCompressedSize to get the smallest size fitting the content.
4. Adding a bonus 1. We’ve computed the content view height but we actually need to return… the cell height here. And it’s 1 pixel higher, because of the separator, which height is 1 pt (0.5 for Retina screens on iOS 7, to be exact).
讨论这个解决方案
该解决方案涉及更多计算,然后询问[NSString -boundingRectWithSize:options:attributes:]。但在我看来,后一种方法可以让您将所有设计(约束、字体设置等)直接移到代码中,因为它只给您标签高度,而不是整个单元格。
假设您从顶部和底部有 10pt 的缩进。有了新的更新,您决定将其更改为 5。您必须更改代码,否则它不会反映更改。
当然,计算每个单元格的高度需要更多的计算。幸运的是,在 iOs7 中引入了新的 UITableView 委托方法:tableView:estimatedHeightForRowAtIndexPath:。它大大减少了计算并提高了性能。
我确实相信,你应该使用这篇文章中描述的方法(尽管事实上,iOs6 可能存在一些性能问题。我认为现在只有 5-10% 的 iOs6 用户并且正在减少。)