最近在使用Masonry时出现一个布局问题,如下图:
WX20170525-102233.png正常显示:
WX20170525-102303.png布局需求是,最左侧头像完整显示,姓名完整显示,性别和年领完整显示,病名紧贴右侧,左侧不能遮挡年龄,病名过长可以不显示完全。
开始有问题的布局代码:
[self.headImageView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.contentView).offset(12.5);
make.size.mas_equalTo(CGSizeMake(45, 45));
make.centerY.equalTo(self.contentView);
}];
[self.lbPatientName mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.headImageView.mas_right).with.offset(7);
make.top.equalTo(self.headImageView).with.offset(2.5);
}];
[self.lbPatientAge mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.lbPatientName.mas_right).offset(10);
make.centerY.equalTo(self.lbPatientName);
}];
[self.btnIllDiagnose mas_makeConstraints:^(MASConstraintMaker *make) {
make.centerY.equalTo(self.lbPatientName);
make.right.equalTo(self.contentView).offset(-15);
make.left.greaterThanOrEqualTo(self.lbPatientAge.mas_right).offset(3);
}];
这样布局的话当病名过长时,会出现性别年龄被遮挡的情况,如上图一。
解决办法:
因为我们没有给姓名、病名和性别年龄设定固定宽度,所以系统在自动布局的时候并不知道哪个应该被完整显示,哪个可以不完整显示。所以我们要给控件设置布局优先级:
修改后代码如下:
[self.headImageView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.contentView).offset(12.5);
make.size.mas_equalTo(CGSizeMake(45, 45));
make.centerY.equalTo(self.contentView);
}];
[self.lbPatientName mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.headImageView.mas_right).with.offset(7);
make.top.equalTo(self.headImageView).with.offset(2.5);
}];
[self.lbPatientAge mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.lbPatientName.mas_right).offset(10);
make.centerY.equalTo(self.lbPatientName);
}];
[self.btnIllDiagnose mas_makeConstraints:^(MASConstraintMaker *make) {
make.centerY.equalTo(self.lbPatientName);
make.right.equalTo(self.contentView).offset(-15);
make.left.greaterThanOrEqualTo(self.lbPatientAge.mas_right).offset(3);
}];
// 设置优先级
[self.lbPatientName setContentCompressionResistancePriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisHorizontal];
[self.lbPatientAge setContentCompressionResistancePriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisHorizontal];
[self.btnIllDiagnose setContentCompressionResistancePriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];
设置优先级方法:
- (void)setContentCompressionResistancePriority:(UILayoutPriority)priority forAxis:(UILayoutConstraintAxis)axis NS_AVAILABLE_IOS(6_0);
第一个参数(priority):通俗来讲,不同的优先级,表示显示的完整性的高低,优先级越高,那么在父控件无法在无越界的情况下的情况下,就会优先先把优先级高的控件显示完整,然后再依次显示优先级低的
第二个参数(axis):代表在什么方向上进行优先级限制
这样显示就正常了:
WX20170525-104016.png
网友评论