在iOS6之前,苹果系统的图文混排技术使用coreText:如果需要使用可以使用第三方框架(纯C语言)
iOS6使用NSAttributedString、NSMutableAttributedString
iOS7 使用textKit
方法一:
NSMutableAttributedString
*string = [[NSMutableAttributedString
alloc]initWithString:@"yz谁都会发生地方"];
设置某个距离文字的颜色
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, 2)];
[string addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(0, 2)];
设置下划线
[string addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleDouble) range:NSMakeRange(1, 3)];
添加图片
NSTextAttachment *attach = [[NSTextAttachment alloc]init];
attach.image = [UIImage imageNamed:@"placehold"];
可以根据字体的大小设置图片的大小,width和height为字体的size
attach.bounds = CGRectMake(0, 0, 20, 20);
将图片转为NSAttributedString
设置某个距离文字的颜色
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, 2)];
[string addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(0, 2)];
设置下划线
[string addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleDouble) range:NSMakeRange(1, 3)];
添加图片
NSTextAttachment *attach = [[NSTextAttachment alloc]init];
attach.image = [UIImage imageNamed:@"placehold"];
可以根据字体的大小设置图片的大小,width和height为字体的size
attach.bounds = CGRectMake(0, 0, 20, 20);
将图片转为NSAttributedString
NSAttributedString
*attachString = [NSAttributedString
attributedStringWithAttachment:attach];
将NSAttributedString拼接在string后
[注意:NSMutableAttributedString 只能拼接NSMutableAttributedString、NSAttributedString]
将NSAttributedString拼接在string后
[注意:NSMutableAttributedString 只能拼接NSMutableAttributedString、NSAttributedString]
[string
appendAttributedString:attachString];
self.textView.attributedText
= string;
方法二:
使用webView和html语言以及css样式 进行图文混排 但是系统消耗较大,且webView有内存泄露
//webView图文混排
NSString
*html =
@"<font color='red'></font><img src='http://'>";
UIWebView
*webView = [[UIWebView
alloc]initWithFrame:self.view.bounds];
[webView
loadHTMLString:html
baseURL:nil];