Masonry学习之UILabel

本文通过实例演示如何使用UILabel实现自适应布局,并调整其高度和宽度以适应不同长度的文本内容。介绍了UILabel的基本配置方法及如何利用Auto Layout来管理 UILabel 的位置与大小。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先看效果:
这里写图片描述

代码:

- (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的高度和宽度都会随着内容的变化而变化,其用意我不是很理解。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值