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

你。 提交于 2019-12-11 23:07:23

问题


I want to use the Masonry to show two labels (UILabel) in the a line (view). But the left label is much wider than the right one. They shows like that in this picture.(The green label and yellow label.)

The content compression of them are UILayoutPriorityRequired, I want the left side of the left label is equal to its superview and the right side of the right label is equal to its superview. Then how to make the width of each label show depending on its content with even more labels in a view?

Here is my code:

_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:


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



来源:https://stackoverflow.com/questions/33605379/when-two-labels-show-side-by-side-with-using-the-masonry-how-to-make-the-width

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!