您的位置:首页 > 产品设计 > UI/UE

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

2016-10-27 17:29 465 查看

一、 用户场景:

实现微信、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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐