UILabel for Masonry Learning

First see the effect:

Code:

- (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);// This line of code is the original sample code. Using it will cause a crash for an unknown reason. The following line is temporarily replaced
        make.top.equalTo(self.longLabel.bottom);
        make.right.equalTo(self.right).insets(kPadding);
    }];

    return self;
}

Here the UILabel settings are more general, while the constraints of long label and short label are left, top, right, top, respectively.

- (void)layoutSubviews {
    [super layoutSubviews];

    // for multiline UILabel's you need set the preferredMaxLayoutWidth
    // Multiline UILabel requires preferredMaxLayoutWidth to be set
    // you need to do this after [super layoutSubviews] as the frames will have a value from Auto Layout at this point
    // You must set preferredMaxLayoutWidth after [super layoutSubviews] in order for frames to be valuable
    // 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
    // Layout again, because frames need to be recalculated based on preferredLayoutWidth
    [super layoutSubviews];
}

I changed the text and did some tests. It didn't feel good.For a UILabel, the most common method used before was to have a fixed width and a height adaptive, and in this case, the height and width of the UILabel will change with the content, which I don't understand very well.

Posted on Mon, 06 Jul 2020 11:38:41 -0400 by ltd