图文混排

在实际项目开发中,我吗经常会遇到一段文字既要显示文字又要显示图片,例如我们经常使用的QQ、微信的聊天对话框,表情和文字共存就是一种典型的图文混排。下面介绍通过富文本来实现图文混排。

1.修改文字的样式

// 1.创建一个富文本
NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:@"哈哈哈哈哈哈哈123456"];
// 2.修改富文本中的不通过文字样式
[attri addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(1, 3)];
[attri addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(1, 3)];
// 设置数字为红色
[attri addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(7, 6)];
[attri addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30] range:NSMakeRange(7, 6)];

2.文字中添加图片

 // 1.添加表情
NSTextAttachment *attch = [[NSTextAttachment alloc] init];
// 表情图片
attch.image = [UIImage imageNamed:@"img1"];
// 设置图片大小
attch.bounds = CGRectMake(0, 0, 30, 30);
// 创建带有图片的富文本
NSAttributedString *attri1 = [NSAttributedString attributedStringWithAttachment:attch];
[attri appendAttributedString:attri1];
    
self.attrLabel.attributedText = attri;

3.效果

posted @ 2016-07-29 11:15  Coder-LiLe  阅读(202)  评论(0编辑  收藏  举报