如图,有时候会有这种需求:需要根据后台返回的字符串,把里面的数字,运算符等设置成富文本,其实有很多办法,比如多个lable拼接,比如 写循环遍历字符串等
这里介绍一种拓(更)展(有)性(逼)更(格)好的的方法: 使用正则表达式:

- (void)setupAtrributeStrForLable:(UILabel *)lable normalStr:(NSString *)normalStr{
// 富文本str
NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc] initWithString:normalStr];
// 正则
NSRegularExpression *reg = [NSRegularExpression regularExpressionWithPattern:@"\\d|/" options:NSRegularExpressionCaseInsensitive error:nil];
// 取出range
NSArray *matches = [reg matchesInString:normalStr options:0 range:NSMakeRange(0,normalStr.length)];
// 设置富文本
for(NSTextCheckingResult *result in [matches objectEnumerator]) {
NSRange range = [result range];
[attriStr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"#1DB4FF"] range:range ];
}
lable.attributedText = attriStr;
}
以上代码还可以根据业务需要,封装成一个通用的UILable分类或者工具类
网友评论