首先默認讀者已經知道了Masonry的基本使用。這里講解怎么通過UIView的兩個方法實現布局的優先級。
- (void)setContentHuggingPriority:(UILayoutPriority)priority forAxis:(UILayoutConstraintAxis)axis NS_AVAILABLE_IOS(6_0);
- (void)setContentCompressionResistancePriority:(UILayoutPriority)priority forAxis:(UILayoutConstraintAxis)axis NS_AVAILABLE_IOS(6_0);
其中 - (void)setContentHuggingPriority:(UILayoutPriority)priority forAxis:(UILayoutConstraintAxis)axis;
是用來設置控件抗拉伸的優先級。因為是抗拉伸,我們用兩個寬度比較小的UILabel做示范:
//兩個水平布局的label,兩邊間隔分別是12,中間間隔為8(懂意思就行)
UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectZero];
label1.backgroundColor = [UIColor redColor];
label1.text = @"我是標題";
[self.view addSubview:label1];
[label1 mas_makeConstraints:^(MASConstraintMaker *make) {
make.centerY.equalTo(self.view);
make.left.equalTo(@(12));
}];
UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectZero];
label2.backgroundColor = [UIColor redColor];
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);
}];
如果不添加任何約束是圖一這樣顯示的。那如果我們的需求是label1正常顯示,拉伸label2呢,或者說label2的內容緊跟著label1的內容顯示。
只需要這樣做:
[label1 setContentHuggingPriority:UILayoutPriorityRequired
forAxis:UILayoutConstraintAxisHorizontal];
[label2 setContentHuggingPriority:UILayoutPriorityDefaultLow
forAxis:UILayoutConstraintAxisHorizontal];
顯示結果:
這里解釋一下設置的兩個參數:
很容易明白,對應的1000到50代表優先級從高到低。
UILayoutConstraintAxisHorizontal
橫向布局 UILayoutConstraintAxisVertical
縱向布局
然后是- (void)setContentCompressionResistancePriority:(UILayoutPriority)priority forAxis:(UILayoutConstraintAxis)axis
是用來設置控件抗壓縮的優先級。因為是抗壓縮,我們用兩個寬度比較大的UILabel做示范:
UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectZero];
label1.backgroundColor = [UIColor redColor];
label1.text = @"我是標題啊我是標題啊我是標題啊我是標題啊";
[self.view addSubview:label1];
[label1 mas_makeConstraints:^(MASConstraintMaker *make) {
make.centerY.equalTo(self.view);
make.left.equalTo(@(12));
}];
UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectZero];
label2.backgroundColor = [UIColor redColor];
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);
}];
不加約束的結果是:
因為label1過長,已經把label2擠的就剩一點了。如果我們想優先顯示label2,如下設置:
[label1 setContentCompressionResistancePriority:UILayoutPriorityDefaultLow
forAxis:UILayoutConstraintAxisHorizontal];
[label2 setContentCompressionResistancePriority:UILayoutPriorityRequired
forAxis:UILayoutConstraintAxisHorizontal];
效果如圖:
那如果label1和lebel2非常長呢,不管設置誰的優先級,其中一個都會被擠沒了怎么辦?
make.width.greaterThanOrEqualTo
可以設置寬度最少為多少
make.width.lessThanOrEqualTo
可以設置寬度最多為多少
這個我就不在舉例了,很有必要自己練練手,體驗一下。
以上純屬個人理解,希望對你有所幫助,如果有不對的地方歡迎指出交流。
如有其它問題也歡迎留言,一起分享學習!