父视图根据label的高度自适应调整:
需要设置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 = @"苹果iOS15即将登场,界面设计焕然一新,比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 = @"虽然官方并没有举行任何预热活动,但事实上,目前外网已经传出了诸多关于iOS15系统的消息。综合来看,相比iOS14,iOS15仍是以提升体验为主,并不会有太多亮眼的新功能。";
}
结果如下:
image.png