使用富文本在lable上展示不同颜色的文字,自定义label高度,自定义行间距

本文介绍了如何使用富文本在Label上展示不同颜色的文字,并详细讲解了如何自定义Label的高度和行间距。通过示例代码展示了创建富文本、设置文字颜色、字体和行间距的过程,同时提供了计算Label高度的实用技巧。

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

废话不多说,直接上代码

第一段代码主要是创建富文本,并给文字赋值给label,调整文字的颜色字体行间距等

- (void)createLabel
{
    UILabel * textLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 250, 200, 20)];
    textLabel.backgroundColor = [UIColor yellowColor];
    
    //调整行间距
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 10;// 字体的行间距
    
    //设置字体大小
    textLabel.font = [UIFont systemFontOfSize:15.0];

    textLabel.numberOfLines = 0;
    NSDictionary * attribute = @{NSFontAttributeName:[UIFont systemFontOfSize:15.0],NSParagraphStyleAttributeName:paragraphStyle};
    NSMutableAttributedString * str = [[NSMutableAttributedString alloc] initWithString:@"如果一个属性总是使用同一个初始值,可以为其设置一个默认值。无论定义默认值还是在构造器中赋值,最终它们实现的效果是一样的,只不过默认值将属性的初始化和属性的声明结合的更紧密。使用默认值能让你的构造器更简洁、更清晰,且能通过默认值自动推导出属性的类型;同时,它也能让你充分利用默认构造器、构造器继承(后续章节将讲到)等特性。" attributes:attribute];
    
    //设置字体不同的颜色
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 50)];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(50, str.length - 50)];
     [textLabel setAttributedText:str];
    [self addSubview:textLabel];
    
    //计算文字高度并调整lable高度
    CGFloat height = [self setNameLabelWithText:str attribute:attribute];
    textLabel.frame = CGRectMake(10, 250, 200, height);
    
}


第二段通过文字属性计算label的高度,这个方法在开发过程中会经常用到。

- (CGFloat)setNameLabelWithText:(NSMutableAttributedString *)text attribute:(NSDictionary *)attribute
{
    NSString * str = [text string];
    CGRect textRext = [str boundingRectWithSize:CGSizeMake(200, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attribute context:nil];
    CGFloat height = textRext.size.height;
    return height;
    
}

运行结果是酱紫的



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值