【发布时间】:2023-04-11 04:40:01
【问题描述】:
关于如何在其中使用 Autolayout 和 TextView 制作动态单元格高度存在很多问题。故事是这样的
我关注这篇文章iOS dynamic table view cells with varying row height and Autolayout。在这种情况下,我们将文章中的第 2 个标签替换为 TextView,具有相同的约束集
TextView 没有作为标签的固有内容大小。所以我们必须使用
sizeThatFits并在TextView上创建高度约束,像这样。
此高度限制是来自 Nib 的 IBOutlet
ViewController.m
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
Item *item = self.dataSource.items[indexPath.row];
[self.prototypeCell configureWithModel:item];
[self.prototypeCell updateConstraintsIfNeeded];
[self.prototypeCell layoutIfNeeded];
self.prototypeCell.textViewHeightConstraint.constant = [self.prototypeCell.textView sizeThatFits:CGSizeMake(self.prototypeCell.frame.size.width, CGFLOAT_MAX)].height;
[self.prototypeCell updateConstraintsIfNeeded];
[self.prototypeCell layoutIfNeeded];
return [self.prototypeCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
}
CustomCell.m
- (void)configureWithModel:(Item *)model {
self.textView.text = model.content;
}
- 然后我在控制台中看到
Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to找出你没想到的; (2) 找到添加的代码 不需要的约束或约束并修复它。 (注:如果你看到 NSAutoresizingMaskLayoutConstraints 你不明白的,参考 到 UIView 属性的文档 翻译AutoresizingMaskIntoConstraints) ( "", "", "", "", “” )
Will attempt to recover by breaking constraint <NSLayoutConstraint:0x7fa3e3988a90 UITextView:0x7fa3e210f000.height == 200>
这里可以看到Autolayout系统去掉了TextView的高度限制。
这里的问题是我们更新了TextView上的高度约束,但是单元格的contentView似乎忽略了这个。
我知道这个动态高度的关键是子视图(Label,TextView)必须确定它自己的大小(Label有它自己的内在内容大小,对于TextView我们手动设置它的高度约束)所以contentSize是然后计算
我错过了什么?
【问题讨论】:
-
您的 textViewHeightConstraint 是 CustomCell 中的 IBOutlet 吗?
-
@BHendricks 是的,是的
-
你能在 IB 中显示 textview 的约束吗?您是否最初将其限制为 200(文本视图的高度),然后尝试以编程方式更改它?
-
@BHendricks 200 是
sizeThatFits的结果,IB 中高度约束的初始值是另一个值 -
你有没有试过在设置约束后强制布局?我只是查看了执行此类行为的代码,并在代码中手动设置约束后使用 layoutSubviews() 强制布局。
标签: ios textview autolayout constraints