需求:对字符串中的金额的颜色修改
传统方法:遍历查找
NSString *str = @"投资券5.89元";
if ([str containsString:@"元"])
{
NSString *formStr = @"1234567890.";
NSArray *arr = [str componentsSeparatedByString:@"元"];
NSString *targetStr = arr.firstObject;
NSInteger targetLoc;
if ([formStr containsString:[targetStr substringWithRange:NSMakeRange(targetStr.length-1, 1)]])
{
for (NSInteger i=targetStr.length-1; i>=0; i--)
{
if (![formStr containsString:[targetStr substringWithRange:NSMakeRange(i, 1)]])
{
targetLoc = i+1;
break;
}
}
NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:model.desc];
[attributedStr addAttribute:NSForegroundColorAttributeName value:UI_THEME_COLOR range:NSMakeRange(targetLoc, targetStr.length-targetLoc)];
self.descLabel.text = nil;
self.descLabel.attributedText = attributedStr;
}
else
{
self.descLabel.text = str;
}
}
else
{
self.descLabel.text = model.desc;
}
正则查找
NSString *str = @"投资券5.89元";
NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc]initWithString:str];
NSRange range = [str rangeOfString:@"\\d[\\d.,]*(?=元)" options:NSRegularExpressionSearch];
if (range.location != NSNotFound) {
NSString *subStr = [str substringWithRange:range];
NSLog(@"%@", subStr);
[attStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
}
self.moneyLabel.attributedText = attStr;
效果图
网友评论