天天看点

Masonry学习之UILabel

先看效果:

Masonry学习之UILabel

代码:

- (id)init {
    self = [super init];
    if (!self) return nil;

    // text courtesy of http://baconipsum.com/

    self.shortLabel = UILabel.new;
    self.shortLabel.numberOfLines = 1;
    self.shortLabel.textColor = [UIColor purpleColor];
    self.shortLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    self.shortLabel.text = @"Bacon";
    self.shortLabel.backgroundColor = [UIColor redColor];
    [self addSubview:self.shortLabel];

    self.longLabel = UILabel.new;
    self.longLabel.numberOfLines = 8;
    self.longLabel.textColor = [UIColor darkGrayColor];
    self.longLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    self.longLabel.text = @"Bacon ipsum dolor sit amet spare ribs fatback kielbasa salami, tri-tip jowl pastrami flank short loin rump sirloin. Tenderloin frankfurter chicken biltong rump chuck filet mignon pork t-bone flank ham hock.";
    self.longLabel.backgroundColor = [UIColor greenColor];
    [self addSubview:self.longLabel];

    [self.longLabel makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.left).insets(kPadding);
        make.top.equalTo(self.top).insets(kPadding);
    }];

    [self.shortLabel makeConstraints:^(MASConstraintMaker *make) {
        //make.top.equalTo(self.longLabel.lastBaseline);// 该行代码为原示例代码,使用它会造成崩溃,原因未知,以下一行暂时替代
        make.top.equalTo(self.longLabel.bottom);
        make.right.equalTo(self.right).insets(kPadding);
    }];

    return self;
}
           

这里UILabel的设置都比较常规了,而长label和短label的约束只分别设置了left、top和right、top;

- (void)layoutSubviews {
    [super layoutSubviews];

    // for multiline UILabel's you need set the preferredMaxLayoutWidth
    // 多行UILabel需要设置preferredMaxLayoutWidth
    // you need to do this after [super layoutSubviews] as the frames will have a value from Auto Layout at this point
    // 你必须在[super layoutSubviews]之后设置preferredMaxLayoutWidth,以为此时frames才会有值
    // stay tuned for new easier way todo this coming soon to Masonry

    CGFloat width = CGRectGetMinX(self.shortLabel.frame) - kPadding.left;
    width -= CGRectGetMinX(self.longLabel.frame);
    self.longLabel.preferredMaxLayoutWidth = width;

    // need to layoutSubviews again as frames need to recalculated with preferredLayoutWidth
    // 再次布局,因为frames需要根据preferredLayoutWidth重新计算
    [super layoutSubviews];
}           

我改变了一下文字内容进行了一些测试,感觉效果并不好。对于UILabel,以前用的最多的方式就是固定宽度而高度进行自适应,而这个例子的中,UILabel的高度和宽度都会随着内容的变化而变化,其用意我不是很理解。

继续阅读