当两个标签显示并排使用的砌体,如何让这取决于其内容的每个标签显示的宽度是多少?(When two l

2019-11-04 03:14发布

我想使用的砌体显示在一条线(图)两个标签(的UILabel)。 但是,左侧的标签是比右边的宽得多。 他们表示像在这张图片。(绿色标签和黄色标签)。

它们的内容压缩的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];

Answer 1:

http://swiftcn.io/topics/32 Set content hugging and content compression. (中国人吧?)



文章来源: When two labels show side by side with using the Masonry, how to make the width of each label show depending on its content?