首先默认读者已经知道了Masonry的基本使用。这里讲解怎么通过UIView的两个方法实现布局的优先级。
- (void)setContentHuggingPriority:(UILayoutPriority)priority forAxis:(UILayoutConstraintAxis)axisNS_AVAILABLE_IOS(6_0);
- (void)setContentCompressionResistancePriority:(UILayoutPriority)priority forAxis:(UILayoutConstraintAxis)axisNS_AVAILABLE_IOS(6_0);
其中- (void)setContentHuggingPriority:(UILayoutPriority)priority forAxis:(UILayoutConstraintAxis)axis;是用来设置控件抗拉伸的优先级。因为是抗拉伸,我们用两个宽度比较小的UILabel做示范:
//两个水平布局的label,两边间隔分别是12,中间间隔为8(懂意思就行)UILabel*label1 = [[UILabelalloc] initWithFrame:CGRectZero];label1.backgroundColor = [UIColorredColor];label1.text =@"我是标题";[self.view addSubview:label1]; [label1 mas_makeConstraints:^(MASConstraintMaker *make) { make.centerY.equalTo(self.view); make.left.equalTo(@(12)); }];UILabel*label2 = [[UILabelalloc] initWithFrame:CGRectZero];label2.backgroundColor = [UIColorredColor];label2.text =@"我是描述";[self.view addSubview:label2];[label2 mas_makeConstraints:^(MASConstraintMaker *make) { make.centerY.equalTo(label1); make.left.equalTo(label1.mas_right).offset(8); make.right.equalTo(self.view).offset(-12);}];

图一@2x.png
如果不添加任何约束是图一这样显示的。那如果我们的需求是label1正常显示,拉伸label2呢,或者说label2的内容紧跟着label1的内容显示。
只需要这样做:
[label1 setContentHuggingPriority:UILayoutPriorityRequiredforAxis:UILayoutConstraintAxisHorizontal];[label2 setContentHuggingPriority:UILayoutPriorityDefaultLowforAxis:UILayoutConstraintAxisHorizontal];
显示结果:

图二.png
这里解释一下设置的两个参数:

图三.png
很容易明白,对应的1000到50代表优先级从高到低。

图四.png
UILayoutConstraintAxisHorizontal横向布局UILayoutConstraintAxisVertical纵向布局
然后是- (void)setContentCompressionResistancePriority:(UILayoutPriority)priority forAxis:(UILayoutConstraintAxis)axis是用来设置控件抗压缩的优先级。因为是抗压缩,我们用两个宽度比较大的UILabel做示范:
UILabel*label1 = [[UILabelalloc] initWithFrame:CGRectZero];label1.backgroundColor = [UIColorredColor];label1.text =@"我是标题啊我是标题啊我是标题啊我是标题啊";[self.view addSubview:label1]; [label1 mas_makeConstraints:^(MASConstraintMaker *make) { make.centerY.equalTo(self.view); make.left.equalTo(@(12)); }];UILabel*label2 = [[UILabelalloc] initWithFrame:CGRectZero];label2.backgroundColor = [UIColorredColor];label2.text =@"我是描述啊我是描述啊我是描述啊我是描述啊";[self.view addSubview:label2];[label2 mas_makeConstraints:^(MASConstraintMaker *make) { make.centerY.equalTo(label1); make.left.equalTo(label1.mas_right).offset(8); make.right.equalTo(self.view).offset(-12);}];
不加约束的结果是:

图五.png
因为label1过长,已经把label2挤的就剩一点了。如果我们想优先显示label2,如下设置:
[label1 setContentCompressionResistancePriority:UILayoutPriorityDefaultLowforAxis:UILayoutConstraintAxisHorizontal];[label2 setContentCompressionResistancePriority:UILayoutPriorityRequiredforAxis:UILayoutConstraintAxisHorizontal];
效果如图:

图七.png
那如果label1和lebel2非常长呢,不管设置谁的优先级,其中一个都会被挤没了怎么办?
make.width.greaterThanOrEqualTo可以设置宽度最少为多少
make.width.lessThanOrEqualTo可以设置宽度最多为多少
网友评论