iOS 7/8 UITableView Cell:两个具有dynamic高度的UILabel,以及可变行高的自动布局

所以当我只有一个根据string长度改变高度的标签时,我可以用自动布局设置dynamic高度尺寸。 我的问题是,如果我添加另一个应该这样做的UILabel,事情不会奏效。

我将内容拥抱优先级和压缩阻力设置为1000这两个==我得到不明确的警告

如果我将第二个UILabel的内容拥抱(垂直)设置为999或250,那么它的效果很好,但是只有第二个标签有两个或更多的线。 如果第二个标签为空或仅有一行,则heightForRowAtIndexPath systemLayoutSizeFittingSize:UILayoutFittingCompressedSize height会返回较大的值,并且这些单元格具有较大的空格。

我也玩过内在大小:默认或占位符(有几个高度和宽度),但它也没有帮助。

任何人有什么build议可以做什么?

我终于搞定了。 该解决scheme是我明确设置首选宽度当前帧的宽度。 所以基本上检查大小检查器中的标签>首选宽度中的显式复选标记。

ref: http : //www.raywenderlich.com/73602/dynamic-table-view-cell-height-auto-layout下载示例代码并查看故事板设置。

对我来说,这是几件事情的结合。

  • 除了设置内容拥抱和阻力正确
  • 我不得不做一个UILabel的子类来处理标签的preferredMaxLayoutWidth
  • 并更正intrinsicContentSize中的错误

UILabel子类最终看起来像这样:

@implementation LabelDynamicHeight - (void)layoutSubviews { [super layoutSubviews]; self.preferredMaxLayoutWidth = self.frame.size.width; [super layoutSubviews]; } - (void)setBounds:(CGRect)bounds { [super setBounds:bounds]; if (self.numberOfLines == 0) { CGFloat boundsWidth = CGRectGetWidth(bounds); if (self.preferredMaxLayoutWidth != boundsWidth) { self.preferredMaxLayoutWidth = boundsWidth; [self setNeedsUpdateConstraints]; } } } - (CGSize)intrinsicContentSize { CGSize size = [super intrinsicContentSize]; if (self.numberOfLines == 0) { // There's a bug where intrinsic content size may be 1 point too short size.height += 1; } return size; } @end 

除此之外,在获取tableView heightForRowAtIndexPath:之前调用layoutIfNeeded的单元格systemLayoutSizeFittingSize:在contentView上使用systemLayoutSizeFittingSize:方法之前,使约束准备就绪。 看起来像这样:

 - (CGFloat)tableView:( UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = ...; CGFloat height = cell.frame.size.height; if (cell.dynamicHeight) { // https://stackoverflow.com/a/26351692/1840269 [cell layoutIfNeeded]; height = cell.frame.size.height; CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]; if (size.height > height) height = size.height; } return height; } 

参考文献:

  • 首选内容拥抱和阻力: https : //stackoverflow.com/a/16281229/1840269
  • preferredMaxLayoutWidth操作的描述: https : //www.objc.io/issues/3-views/advanced-auto-layout-toolbox/
  • 使用intrinsicContentSize修复对UILabel子类的启示: https : //github.com/smileyborg/TableViewCellWithAutoLayoutiOS8/issues/7

对于我来说,将内容拥有优先级和内容压缩阻力优先级降低到正如所期望的一样。