自动调整尺寸的UITableViewCell: MyTableViewCell.m
-(void) viewDidLoad{
UIView *sample = [[UIView alloc] init];
[self.contentView addSubview: sample];
//Fake code here. Let sample view fill the whole contentView:
Constraint1: sample.leading = contentView.leading;
Constraint2: sample.trailing = contentView.trailing;
Constraint3: sample.top = contentView.top;
Constraint4: sample.bottom = contentView.bottom;
Constraint5: sample.height = 20;
NSLayoutConstraint:activateConstriant(constraints 1-5);
}
这段代码可以运行,MyTableViewCell
的高度为20。
但是,我希望在运行时(此单元格添加到UITableView后)更改高度,因此我在 MyTableViewCell.m 中添加了一个新方法
-(void) updateHeight:(CGFloat)newHeight{
//Fake code here. change the constant of constraint1
Constraint1 = get reference of Constraint1 in viewDidLoad();
Constraint1.constant = newHeight
}
我运行了代码并调用了
updateHeight:10
,然后收到了日志警告:
我认为在2017-03-16 16:23:11.102858 [14541:568021] [LayoutConstraints] 无法同时满足约束条件。以下列表中的至少一个约束条件可能不是您想要的。请尝试: (1) 查看每个约束条件并尝试找出哪些约束条件不符合您的预期; (2) 找到添加不需要的约束条件的代码并进行修复。 ( "", "", "", "" ) 将尝试通过破坏约束来恢复
viewDidLoad
中创建的约束自动生成了其他约束,比如 contentView.height=20
,而对原始约束的更改与系统所创建的约束发生冲突。我试图更改示例视图的前导而不是高度,在
updateHeight:
中执行更改,它奏效了!因为前导的更改不会影响 contentView 自己的高度约束?在这种情况下,我该如何动态地更改自动布局?
谢谢~~~
sample.translatesAutoresizingMaskIntoConstraints = NO
。往往情况下,这能解决问题。 - Rikh