最近在使用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