步骤以下:app
NSMutableAttributedString 建立一个富文本对象字体
调用富文本的对象方法 addAttribute:(NSString * )value:(id) range:(NSRange) 来修改对应range范围中 attribute属性的 value值spa
Objective-Corm
1对象 2图片 3string 4it 5table 6import 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号字体大小,颜色为红色样式
步骤以下:
建立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; |