RichText
RichText
是基于 NSAttributedString
的一层轻量封装,可以用它来替换 NSAttributedString
/NSMutableAttributedString
,实现各种富文本。
使用 NSAttributedString
创建富文本是一件繁琐闹心的事情,有很多又长又难以记住的属性字典,不仅写作起来耗时,代码的可读性也不是很好。
RichText 可以通过方法链流畅地创建一个富文本。添加属性、改变范围、匹配正则、拼接字符串,都只需调用一个简单的方法。
举例:
使用 NSAttributedString
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithString:@"恭喜你获得50金币,以及10元现金奖励,可提现"];
[attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:NSMakeRange(0, attrStr.length)];
NSError *err = nil;
NSRegularExpression *regExp = [NSRegularExpression regularExpressionWithPattern:@"\\d" options:NSRegularExpressionCaseInsensitive error:&err];
NSAssert(err == nil, err.localizedDescription);
[regExp enumerateMatchesInString:attrStr.string options:NSMatchingReportCompletion range:NSMakeRange(0, attrStr.length) usingBlock:^(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL * _Nonnull stop) {
if (result.range.location != NSNotFound) {
[attrStr addAttribute:NSForegroundColorAttributeName value:UIColor.redColor range:result.range];
}
}];
[attrStr addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:14] range:NSMakeRange(attrStr.length - 3, 3)];
使用 RichText
@"恭喜你获得50金币,以及10元现金奖励,可提现"
.setFont(UIFont.regular(14))
.matches(@"\\d")
.setColor(UIColor.redColor)
.last(3)
.setFont(UIFont.bold(14));
示例
要运行示例项目,首先克隆 Git 仓库,然后在示例目录中运行 pod install
安装
RichText 通过 CocoaPods 提供。要安装它,只需在 Podfile 中添加以下行:
pod 'RichText'
作者
许可协议
RichText 采用 MIT 许可协议。更多信息请参阅 LICENSE 文件。