UILabel-抗拉伸和抗压缩性

场景: 三段文字,第一个和第二个左右排列,顶部对齐且第二段内容的左边与第一段内容的右边距离为20px,第三个的顶部距离上面两个的底部为20px,且三段内容距离视图边界均为30px;通常的,使用三个UILabel控件来展示此UI布局。

  • 声明3个UILabel属性
@property (nonatomic, strong) UILabel *oneLabel;//上 -左
@property (nonatomic, strong) UILabel *twoLabel;//上 -右
@property (nonatomic, strong) UILabel *threeLabel;//下
  • 这里懒加载创建控件
- (UILabel *)oneLabel
{
    if (!_oneLabel) {
        _oneLabel = [[UILabel alloc] init];
        _oneLabel.textColor = [UIColor redColor];
        _oneLabel.font = [UIFont systemFontOfSize:15];
    }
    return _oneLabel;
}

- (UILabel *)twoLabel
{
    if (!_twoLabel) {
        _twoLabel = [[UILabel alloc] init];
        _twoLabel.textColor = [UIColor orangeColor];
        _twoLabel.font = [UIFont systemFontOfSize:15];
        _twoLabel.numberOfLines = 0;//换行
    }
    return _twoLabel;
}

- (UILabel *)threeLabel
{
    if (!_threeLabel) {
        _threeLabel = [[UILabel alloc] init];
        _threeLabel.textColor = [UIColor magentaColor];
        _threeLabel.font = [UIFont systemFontOfSize:15];
        _threeLabel.numberOfLines = 0;//换行
    }
    return _threeLabel;
}
  • 使用Masonry来布局
[self.view addSubview:self.oneLabel];
    [self.view addSubview:self.twoLabel];
    [self.view addSubview:self.threeLabel];
    
    self.oneLabel.text = @"抗压缩和抗拉伸性";
    self.twoLabel.text = @"遇见你,我变得很低很低,一直低到尘埃里去,但我的心是欢喜的。并且在那里开出一朵花来。";
    self.threeLabel.text = @"我行过许多地方的桥,看过许多次数的云,喝过许多类的酒,却只爱过一个正当最好年龄的人";
    
    [self.oneLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(@15);
        make.top.mas_equalTo(20 + 64);
    }];
    
    [self.twoLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(_oneLabel.mas_trailing).mas_offset(10);
        make.trailing.equalTo(@-15);
        make.top.equalTo(_oneLabel);
    }];
    
    [self.threeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(_oneLabel);
        make.top.equalTo(_twoLabel.mas_bottom).mas_offset(15);
        make.trailing.equalTo(_twoLabel);
    }];
  • 如此布局,运行效果
UILabel-抗拉伸和抗压缩性_第1张图片
Simulator Screen Shot .png

这样看,其实并没有什么问题,但如果twoLabel的text的内容不确定,比如: self.twoLabel.text = @"遇见你";

运行效果:

UILabel-抗拉伸和抗压缩性_第2张图片
Simulator Screen Shot.png

很显然,此时效果不符合要求。

  • 设置label的背景色
UILabel-抗拉伸和抗压缩性_第3张图片
Simulator Screen Shot.png

看到第一个label被水平拉伸了,导致视觉上看到第二个label依赖于右侧约束。 为了达到要求的布局,需要给左边label设置抗拉伸性。

  • 设置左边label的抗拉伸性
//抗拉伸性 越高越不容易被拉伸
    [self.oneLabel setContentHuggingPriority:UILayoutPriorityRequired
                                     forAxis:UILayoutConstraintAxisHorizontal];
  • 一般情况下,需要防止其拉伸的 有时也同样需要防止其被压缩,所以 通常一起设置其压缩性
//抗压缩性 越高越不容易被压缩
    [self.oneLabel setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
  • 最终效果:
UILabel-抗拉伸和抗压缩性_第4张图片
Simulator Screen Shot.png
  • 按住command + 设置拉伸和压缩性的代码 进入SDK,发现它们被声明于UIView,因为UILabel继承于UIView,自然有此方法;那么UIButton(->UIControl->UIView)等继承于UIView的控件也有此方法。

代码

你可能感兴趣的:(UILabel-抗拉伸和抗压缩性)