setContentCompressionResistancePriority和setContentHuggingPriority使用總結

說實話我花了不少時間才真正理解setContentCompressionResistancePriority和setContentHuggingPriority的用法。

[label1 setContentCompressionResistancePriority:758 forAxis:(UILayoutConstraintAxisHorizontal)];

[label1 setContentHuggingPriority:300 forAxis:(UILayoutConstraintAxisHorizontal)];

setContentCompressionResistancePriority(抗壓縮),這個值越低,就會在寬度不夠的情況下,被壓縮。常見的視圖默認給的值是UILayoutPriorityDefaultHigh = 750。若是多個視圖是默認值,會被系統認爲更早被addSubview的視圖該值更小!

setContentHuggingPriority(抗拉伸),這個值越低,就會在寬度多餘的情況下,被拉伸。常見的視圖默認給的值是UILayoutPriorityDefaultLow = 250。若是多個視圖是默認值,會被系統認爲更早被addSubview的值更小!

下面舉個栗子驗證下:

import "CompressionAndHuggingViewController.h"

#import <Masonry.h>

 

@interface CompressionAndHuggingViewController ()

 

@property (nonatomic, weak) UILabel * label1;

 

@property (nonatomic, weak) UILabel * label2;

 

@property (nonatomic, weak) UILabel * label3;

 

@end

 

@implementation CompressionAndHuggingViewController

 

- (UIStatusBarStyle)preferredStatusBarStyle{

    return UIStatusBarStyleLightContent;

}

 

-(void)viewDidLoad{

    [super viewDidLoad];

    [self setUI1];

    self.view.backgroundColor = [UIColor whiteColor];

    _label1.text = @"張發給發給";

    _label2.text = @"髒了發浪浪浪蘭陵古娜拉你敢來給你";

    _label3.text = @"2019.12.22";

}

 

- (void)setUI1{

    

    UILabel *label1 = [[UILabel alloc] init];

    label1.textColor = @"#212121".toColor;

    label1.font = [UIFont systemFontOfSize:16];

    [self.view addSubview:label1];

    _label1 = label1;

    [label1 mas_makeConstraints:^(MASConstraintMaker *make) {

        make.top.offset(100);

        make.left.offset(10);

    }];

    

    [label1 setContentCompressionResistancePriority:758 forAxis:(UILayoutConstraintAxisHorizontal)];

    [label1 setContentHuggingPriority:300 forAxis:(UILayoutConstraintAxisHorizontal)];

    

    UILabel *label2 = [[UILabel alloc] init];

    label2.textColor = @"#757575".toColor;

    label2.font = [UIFont systemFontOfSize:16];

    [self.view addSubview:label2];

    _label2 = label2;

    [label2 mas_makeConstraints:^(MASConstraintMaker *make) {

        make.left.equalTo(label1.mas_right).offset(8);

        make.width.greaterThanOrEqualTo(@80).priority(759);

        make.top.equalTo(label1.mas_top);

    }];

    

    UILabel *label3 = [[UILabel alloc] init];

    label3.textColor = @"#757575".toColor;

    label3.textAlignment = NSTextAlignmentRight;

    label3.font = [UIFont systemFontOfSize:16];

    [self.view addSubview:label3];

    _label3 = label3;

    [label3 mas_makeConstraints:^(MASConstraintMaker *make) {

        make.right.offset(-16);

        make.left.equalTo(label2.mas_right).offset(2);

        make.top.equalTo(label1.mas_top);

    }];

    [label3 setContentCompressionResistancePriority:760 forAxis:(UILayoutConstraintAxisHorizontal)];

}

 

@end

發佈了72 篇原創文章 · 獲贊 70 · 訪問量 24萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章