对于复杂的布局,尽量让子view针对父view布局。
在xcode 8 中,使用自动推算高度时, 对tableView进行约束时容易出现约束冲突。
比如:
在cell的contentView中添加一个bgview,bgview中有两个label并排排列,bgview的背景为红色,现在想让bgview根据lablel的文字内容自动缩放宽度,并在contentview居中显示。
1、初始化约束
<div>
WS(weakSelf);
[self.bgView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.offset(10);
make.bottom.offset(-10);
make.centerX.offset(0);
}];
[self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.leading.offset(5);
make.bottom.offset(-5);
}];
[self.clickLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.leading.equalTo(weakSelf.titleLabel.mas_trailing);
make.top.bottom.equalTo(weakSelf.titleLabel);
make.trailing.offset(-5);
}];
</div>
2.在label赋值后更新bgview的约束
<div>
CGSize size = [self.bgView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
[self.bgView mas_updateConstraints:^(MASConstraintMaker *make) {
make.size.mas_equalTo(size);
}];
</div>