在很多 TimeLine 的排版页面,都会用到富文本,多样式的文字展示,以及为某些特殊文字,比如@,# ,以及网址添加点击事件。这里就以为 @ 和 # 添加不同样式和点击事件 和 替换网址为某个特定图片,以及添加点击事件的功能,介绍一下主流应用的两个第三方库,TTTAttributedLabel 和 YYText 的一些用法。
TTTAttributedLabel
TTTAttributedLabel 继承于 UILabel,所以具有 UILabel 所有的属性和方法。通过CoreText绘制富文本。
1、初始化:
由于是继承与UILabel,因此和 UILabel 的初始化相同。
TTTAttributedLabel *label = [TTTAttributedLabel alloc] init];
2、赋值:
TTTAttributedLabel 是比较老的库,当时 UILabel 还并没有 attributedText 属性。通过 setText 进行赋值,在 block 里制定富文本规则。
NSString *message = @"@小明 #旅行计划# 网址是:http://blog.csdn.net/u013749108 完毕"
[label setText:message afterInheritingLabelAttributesAndConfiguringWithBlock:^NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
//label 整体 风格
[mutableAttributedString addAttributes:[self textStyle] range:NSMakeRange(0, message.length)];
//找出 # @
NSArray *matches = [PXStatusUtil checkAllLinksWithOutUrlText:message];
//遍历符合规则的结果
for ( NSTextCheckingResult *match in matches ) {
NSRange wordRange = [match range];
//为符合结果的文字添加富文本属性字典
[mutableAttributedString addAttributes:[self linkStyle] range:wordRange];
}
//找出 url 添加文字样式
NSArray *matches_with_url = [PXStatusUtil checkURLLinksWithText:data.message];
for (NSUInteger i = matches_with_url.count; i > 0;