【iOS开发】在UILabel中同时显示图片和文字,"混排"。

来源:互联网 发布:unity3d 鼠标旋转视角 编辑:程序博客网 时间:2024/05/22 00:32

一、 用户场景:

实现微信、QQ的聊天对话框中,文字和表情同时存在功能,即图文混排。

这里写图片描述

二、思路描述:

(1) 使用富文本方法

UILabel有text这个文本属性,要做到富文本效果,就需要用到一个并不是所有人都知道的富文本属性 attributedText(textView、textField中都有这个属性)。

(2)代码实现:

    // 创建UILabel控件    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 60)];    lab.center = self.view.center;    lab.backgroundColor = [UIColor orangeColor];    // 1.创建一个富文本    NSMutableAttributedString *attri =  [[NSMutableAttributedString alloc] initWithString:@"嘿嘿嘿嘿嘿123456789"];    // 修改富文本中的不同文字的样式    [attri addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, 5)];    [attri addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(0, 5)];    // 设置数字为红色    [attri addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(5, 9)];    [attri addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30] range:NSMakeRange(5, 9)];    // 2.添加表情图片    NSTextAttachment *attch = [[NSTextAttachment alloc] init];    // 表情图片    attch.image = [UIImage imageNamed:@"023[困]@2x.png"];    // 设置图片大小    attch.bounds = CGRectMake(0, 0, 32, 32);    // 创建带有图片的富文本    NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];    [attri insertAttributedString:string atIndex:3];// 插入某个位置    // 用label的attributedText属性来使用富文本    lab.attributedText = attri;    [self.view addSubview:lab];

三、 效果图:

这里写图片描述

Demo下载地址:Demo_AttributedLable

2 0