当两个标签与使用砌体并排显示时,如何根据其内容显示每个标签的宽度?

时间:2015-11-09 08:49:03

标签: ios autolayout uilabel masonry ios-autolayout

我想使用Masonry在一行(视图)中显示两个标签(UILabel)。但是左边的标签要比右边的标签宽得多。 They shows like that in this picture.(The green label and yellow label.)

它们的内容压缩是UILayoutPriorityRequired,我希望左侧标签的左侧等于其超级视图,右侧标签的右侧等于其超级视图。那么如何使每个标签的宽度根据其内容显示在视图中的更多标签?

这是我的代码:

_label1 = [UILabel new];
_label1.backgroundColor = [UIColor yellowColor];
_label1.text = @"label,";

_label2 = [UILabel new];
_label2.backgroundColor = [UIColor greenColor];
_label2.text = @"label,";

[_contentView1 addSubview:_label1];
[_contentView1 addSubview:_label2];

[_label1 mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(_contentView1.mas_top).with.offset(5);
    make.left.equalTo(_contentView1.mas_left).with.offset(2);
    make.height.equalTo(@40);
}];

[_label2 mas_makeConstraints:^(MASConstraintMaker *make) {

    make.left.equalTo(_label1.mas_right).with.offset(2);
    make.top.equalTo(_contentView1.mas_top).with.offset(5);
    make.right.equalTo(_contentView1.mas_right).with.offset(-2);
    make.height.equalTo(@40);
}];

[_label1 setContentHuggingPriority:UILayoutPriorityRequired
                           forAxis:UILayoutConstraintAxisHorizontal];

[_label1 setContentCompressionResistancePriority:UILayoutPriorityRequired
                                         forAxis:UILayoutConstraintAxisHorizontal];

[_label2 setContentHuggingPriority:UILayoutPriorityRequired
                           forAxis:UILayoutConstraintAxisHorizontal];

[_label2 setContentCompressionResistancePriority:UILayoutPriorityRequired
                                         forAxis:UILayoutConstraintAxisHorizontal];

1 个答案:

答案 0 :(得分:0)

http://swiftcn.io/topics/32 设置内容拥抱和内容压缩。 (中国人吧?)