父視圖根據(jù)label的高度自適應(yīng)調(diào)整:
需要設(shè)置label:
1、numberOfLines
2、preferredMaxLayoutWidth 或者 固定label的寬度
3、- (void)setContentHuggingPriority:(UILayoutPriority)priority forAxis:(UILayoutConstraintAxis)axis;
代碼如下:
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
UIView *contentView = [[UIView alloc] init];
[self.view addSubview:contentView];
contentView.backgroundColor = [UIColor redColor];
[contentView mas_makeConstraints:^(MASConstraintMaker *make) {
make.center.equalTo(@0);
make.width.equalTo(@300);
}];
UILabel *label1 = [[UILabel alloc] init];
[contentView addSubview:label1];
[label1 mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(@20);
// make.centerX.equalTo(@0);
make.left.equalTo(@50);
make.right.equalTo(@-50);
}];
label1.numberOfLines = 0;
// label.preferredMaxLayoutWidth = 200;
[label1 setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
label1.backgroundColor = [UIColor whiteColor];
label1.text = @"蘋(píng)果iOS15即將登場(chǎng),界面設(shè)計(jì)煥然一新,比iOS14更漂亮";
UILabel *label2 = [[UILabel alloc] init];
[contentView addSubview:label2];
[label2 mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(label1.mas_bottom).offset(20);
make.left.equalTo(@50);
make.right.equalTo(@-50);
make.bottom.equalTo(@-20);
}];
label2.numberOfLines = 0;
// label.preferredMaxLayoutWidth = 200;
[label2 setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
label2.backgroundColor = [UIColor whiteColor];
label2.text = @"雖然官方并沒(méi)有舉行任何預(yù)熱活動(dòng),但事實(shí)上,目前外網(wǎng)已經(jīng)傳出了諸多關(guān)于iOS15系統(tǒng)的消息。綜合來(lái)看,相比iOS14,iOS15仍是以提升體驗(yàn)為主,并不會(huì)有太多亮眼的新功能。";
}
結(jié)果如下:

image.png