前言
在iOS的日常开发中,会经常使用到富文本。
简单来说,富文本就是一段有属性的字符串,可以包含不同字体、不同字号、不同背景、不同颜色、不同字间距的文字,还可以设置段落、图文混排等属性。
正常在使用富文本的时候,有如下方式:HTML、TextKit、YYKit。一般在长列表的场景下,我们使用性能更高、内存占用更少的TextKit、YYKit。
WebView加载HTML
这个是个常规操作
1 | [self.wbView loadHTMLString:articleString baseURL:nil]; |
与loadRequest
方法相比,loadHTMLString
可以直接读取HTML代码,省去了网络请求的时间,展示速度很快。
不过HTML里面的图片资源还是需要通过网络获取的,如果能够在展示之前就缓存下图片,无需等待,就能够快速的展示了。
如何缓存HTML里面的图片
在Cocoa层使用NSURLProtocol可以拦截所有HTTP请求,所有可以利用NSURLProtocol来缓存文章中的图片。
推荐戴铭的这个Web页面预加载库STMURLCache来预缓存HTML里面的图片。具体的使用方法都在仓库里面。
YYText
集成十分简单,cocoapods就可以。下面看下如何使用:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20NSMutableAttributedString *text = [NSMutableAttributedString new];
UIFont *font = [UIFont systemFontOfSize:16];
NSMutableAttributedString *attachment = nil;
// 嵌入 UIImage
UIImage *image = [UIImage imageNamed:@"dribbble64_imageio"];
attachment = [NSMutableAttributedString yy_attachmentStringWithContent:image contentMode:UIViewContentModeCenter attachmentSize:image.size alignToFont:font alignment:YYTextVerticalAlignmentCenter];
[text appendAttributedString: attachment];
// 嵌入 UIView
UISwitch *switcher = [UISwitch new];
[switcher sizeToFit];
attachment = [NSMutableAttributedString yy_attachmentStringWithContent:switcher contentMode:UIViewContentModeBottom attachmentSize:switcher.size alignToFont:font alignment:YYTextVerticalAlignmentCenter];
[text appendAttributedString: attachment];
// 嵌入 CALayer
CASharpLayer *layer = [CASharpLayer layer];
layer.path = ...
attachment = [NSMutableAttributedString yy_attachmentStringWithContent:layer contentMode:UIViewContentModeBottom attachmentSize:switcher.size alignToFont:font alignment:YYTextVerticalAlignmentCenter];
[text appendAttributedString: attachment];
最后
对比代码可以看到,原生代码描述富文本跟HTML比,既啰嗦又复杂。HTML代码更已读、更容易维护,所以除了长列表外,都建议使用HTML来描述富文本。