- 很多需求会出现如果某段字符串里有数字的话就变色,最重要的是字符串还是随机的,这就坑了!
- 下面就是针对这个问题的解决方案:
- (NSMutableAttributedString*)getString{NSString*detailStr = @"今日总拍品1200辆,您的心愿车56辆,赶紧去看看";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:detailStr];
//找到数字在字符串中得位置
[[self findNumFromStr:detailStr] enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSRange range = [detailStr rangeOfString:obj];
if (range.location != NSNotFound)
{
NSLog(@"found at location = %lu, length = %lu",(unsigned long)range.location,(unsigned long)range.length);
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(range.location, range.length)];
}
else
{
NSLog(@"Not Found");
}
}];
return attributedString;
}
- (NSMutableArray*)findNumFromStr:(NSString*)originalString{
NSMutableArray*numberArray = [NSMutableArray array];
NSString*tempStr;
NSScanner*scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet*numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
while (![scanner isAtEnd]) {
[scanner scanUpToCharactersFromSet:numbers intoString:NULL];
[scanner scanCharactersFromSet:numbers intoString:&tempStr];
if (tempStr && tempStr.length > 0) {
[numberArray addObject:tempStr];
}
tempStr = @"";
}
return numberArray;
}