UILabel-抗拉伸和抗压缩性

2017-07-19  本文已影响742人  CoderCurtis

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

@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;
}
[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);
    }];
Simulator Screen Shot .png

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

运行效果:

Simulator Screen Shot.png

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

Simulator Screen Shot.png

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

//抗拉伸性 越高越不容易被拉伸
    [self.oneLabel setContentHuggingPriority:UILayoutPriorityRequired
                                     forAxis:UILayoutConstraintAxisHorizontal];
//抗压缩性 越高越不容易被压缩
    [self.oneLabel setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
Simulator Screen Shot.png

代码

上一篇 下一篇

猜你喜欢

热点阅读