使用正则表达式专用类NSRegularExpression来查找位置并设置颜色
NSString *string = @"满2科,打88折"
NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc]initWithString:self.string];
attStr.font = [UIFont systemFontOfSize:12.0f weight:UIFontWeightSemibold];
attStr.color = [UIColor blackColor];
NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:@"\\d+\\.?\\d*" options:NSRegularExpressionCaseInsensitive error:nil];
[regular enumerateMatchesInString:self.string options:NSMatchingReportCompletion range:NSMakeRange(0, self.string.length) usingBlock:^(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL * _Nonnull stop) {
NSRange matchRange = result.range;
NSLog(@"range:%@",NSStringFromRange(matchRange));
[attStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:matchRange];
}];
效果图:
image.png










网友评论