UILabel 富文本 显示文字和图片

本文介绍如何在iOS应用中使用UILabel显示富文本,包括文字与图片的结合,通过设置attributedText属性实现复杂的文本展示效果。

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

//    在UILabel上显示文字和图片
    //UIlabel 富文本 字体显示不同颜色
    UILabel *testLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 100, 320, 30)];
    testLabel.backgroundColor = [UIColor lightGrayColor];
    testLabel.textAlignment = NSTextAlignmentCenter;
    NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc] initWithString:@"今天天气不错呀"];
    [AttributedStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20.0] range:NSMakeRange(2, 2)];
    [AttributedStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(2, 3)];
    testLabel.attributedText = AttributedStr;
    [self.view addSubview:testLabel];
    
    //UIlabel 富文本 图文混排
    UILabel *testLabel_2 =[[UILabel alloc]init];
    testLabel_2.frame =CGRectMake(0, 100+50, 200, 100);
    testLabel_2.backgroundColor =[UIColor redColor];
    testLabel_2.textColor = [UIColor greenColor];
    [self.view addSubview:testLabel_2];
    
    NSString *str1 = @"我的";
    NSString *str2 = @"图片";
    // 创建一个富文本
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@",str1,str2]];
    // 修改富文本中的不同文字的样式
    [attri addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, str1.length)];
    [attri addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(0, str1.length)];
    // 设置数字
    [attri addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(str1.length, str2.length)];
    [attri addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30] range:NSMakeRange(str1.length, str2.length)];
    // 创建一个放置图片的富文本
    // 添加表情
    NSTextAttachment *attch = [[NSTextAttachment alloc] init];
    // 表情图片
    attch.image = [UIImage imageNamed:@"biaoqian"];
    // 设置图片大小
    attch.bounds = CGRectMake(0, 0, 40, 40);
    // 创建带有图片的富文本
    NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
    [attri insertAttributedString:string atIndex:3];

    testLabel_2.attributedText = attri;

如下图:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值