iOS学习专题计算机微刊111

Masonry中的优先级(非常实用!)

2017-03-21  本文已影响5360人  郑明明
可能标题不能够完全解释清楚本文到底要描述什么,没关系,我们来举出一个实际的例子,看下图:
红框中的我们发现在第一行一共有三个控件,一个是标题的UILabel(表示为:headLineTabel),一个是宝石的图标UIImageView(表示为:diamondImageView),再有一个是宝石的数量UILabel(表示为:diamondLabel),这时候我们用Masonry编写代码的时候往往一般是这样的思路:
    // 钻石数量label
    [self.contentView addSubview:self.diamondLabel];
    [self.diamondLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.contentView).with.offset(-13 * AutoLayoutScaleX);
        make.top.equalTo(self.contentView).with.offset(13 * AutoLayoutScaleY);
        
    }];
    
    // 钻石imageView
    [self.contentView addSubview:self.diamondImageView];
    [self.diamondImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.diamondLabel.mas_left).with.offset(-2 * AutoLayoutScaleX);
        make.centerY.equalTo(self.diamondLabel);
    }];
    
    // 标题label
    [self.contentView addSubview:self.headLineLabel];
    [self.headLineLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.contentView).with.offset(10 * AutoLayoutScaleX);
        make.centerY.equalTo(self.diamondLabel);
    }];
但是这样的布局所造成的效果肯定不可能是上图所示,因为headLineLabel和diamondImageView之间没有设置约束,所以如果headLine的长度过于长,将会和diamondImageView相互重叠,本文就是要讲解解决这个问题的方法。
// 标题label
    [self.contentView addSubview:self.headLineLabel];
    [self.headLineLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.contentView).with.offset(10 * AutoLayoutScaleX);
        make.centerY.equalTo(self.diamondLabel);
        make.right.mas_lessThanOrEqualTo(self.diamondLabel.mas_left).with.offset(-5 * AutoLayoutScaleX);
    }];
// 设置优先级
    [self.diamondImageView setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
    [self.diamondLabel setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];

    [self.headLineLabel setContentCompressionResistancePriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];
上一篇 下一篇

猜你喜欢

热点阅读