我有一个视图控制器,它有一个 UITableView 实例并使用自动布局约束来呈现它。我想在这个表格视图中有可变的单元格高度。我不想自己计算单元格高度,因为我有一个复杂的单元格内容,由多个标签和图像组成,这些标签和图像可能因单元格而异。我确实相信可以让自动布局单元格调整自身大小,使其包含所有子视图(即在为它们分配文本后使用标签的 sizeToFit 方法?)。
我有一个自定义单元格类,它使用自动布局的视觉约束格式来定位其子视图。我尝试将此处提出的方法及其示例实现合并到此处。
当我初始化表格视图时,我创建了一个与我的数据行长度相等的数组,并通过将值分配给 MyCustomCell 类型的原型单元格来计算每一行的高度,并使用它检索它的高度
[cell systemLayoutSizeFittingSize:UILayoutFittingExpandedSize].height
并将其存储在高度数组中,以便稍后在表格视图的heightForRowAtIndexPath方法中使用它来检索各个单元格的正确单元格高度。
但是,执行所有这些操作后,我最终在 xCode 中遇到了一个不可读的异常NSInternalInconsistencyException,并显示“无法找到传入头 MyCustomCell:0xa8a1430.Width 的传出行头,这永远不会发生。”
这是我的自定义单元格中子视图的初始化:
_titleLabel = [[UILabel alloc] init];
_titleLabel.font = [TSTheme boldThemeFontOfSize:TSThemeFontSizeSmall];
_titleLabel.textColor = [[TSTheme sharedTheme] darkTextColor];
_titleLabel.backgroundColor = [UIColor clearColor];
_titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
_titleLabel.font = [UIFont fontWithName:@"HelveticaNeue-CondensedBold" size:19];
_titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
[self.contentView addSubview:_titleLabel];
_summaryLabel = [[UILabel alloc] init];
_summaryLabel.font = [TSTheme boldThemeFontOfSize:TSThemeFontSizeSmall];
_summaryLabel.backgroundColor = [UIColor clearColor];
_summaryLabel.textColor = [[TSTheme sharedTheme] darkTextColor];
_summaryLabel.translatesAutoresizingMaskIntoConstraints = NO;
_summaryLabel.numberOfLines = 0;
_summaryLabel.preferredMaxLayoutWidth = 250.0f; // required for text wrapping
_summaryLabel.font = [UIFont fontWithName:@"Georgia" size:14];
_summaryLabel.lineBreakMode = NSLineBreakByWordWrapping;
[self.contentView addSubview:_summaryLabel];
_thumbnailView = [[UIImageView alloc] init];
_thumbnailView.translatesAutoresizingMaskIntoConstraints = NO;
[self.contentView addSubview:_thumbnailView];
我的自定义单元格的约束如下
NSDictionary *views = NSDictionaryOfVariableBindings(_titleLabel, _summaryLabel, _thumbnailView);
NSDictionary *metrics = @{@"margin": @"5"};
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(margin)-[_thumbnailView(<=60)]-(margin)-[_titleLabel]-(margin)-|"
options:0
metrics:metrics
views:views]];
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(margin)-[_thumbnailView]-(margin)-|"
options:0
metrics:metrics
views:views]];
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(margin)-[_titleLabel]-(0)-[_summaryLabel]"
options:0
metrics:metrics
views:views]];
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(margin)-[_thumbnailView]-(margin)-[_summaryLabel]-(margin)-|"
options:0
metrics:metrics
views:views]];