Masonry使用之根據(jù)label內(nèi)容高度自適應(yīng)

父視圖根據(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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容