1.修改文字的样式
步骤如下:
NSMutableAttributedString 创建一个富文本对象
调用富文本的对象方法 addAttribute:(NSString * )value:(id) range:(NSRange) 来修改对应range范围中 attribute属性的 value值
Objective-C
1 2 3 4 5 6 7 8 9 10 | // 创建一个富文本 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)]; |
在这段代码中,分别设置了range为(0,5)的文字,也就是哈哈哈哈哈为font20号字体大小,颜色为蓝色的样式;设置了range为(6,9)也就是123456789为font30号字体大小,颜色为红色样式
2.文字中添加图片
步骤如下:
创建NSTextAttachment的对象,用来装在图片
将NSTextAttachment对象的image属性设置为想要使用的图片
设置NSTextAttachment对象bounds大小,也就是要显示的图片的大小
用[NSAttributedString attributedStringWithAttachment:attch]方法,将图片添加到富文本上
1
2
3
4
5
6
7
8
9
10
11
12
13
// 添加表情
NSTextAttachment *attch = [[NSTextAttachment alloc] init];
// 表情图片
attch.image = [UIImage imageNamed:@"d_aini"];
// 设置图片大小
attch.bounds = CGRectMake(0, 0, 32, 32);
// 创建带有图片的富文本
NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
[attri appendAttributedString:string];
// 用label的attributedText属性来使用富文本
self.textLabel.attributedText = attri;