我们正常用的rangeOfString这个API找到第一个符合要求的字符串就直接返回了,当我们要改变所有符合要求的字符串颜色是就不行了,那么我们就找到一个然后截取掉,一直找到最后,把所有的位置用一个数组记录一下,思路很简单,记下来方便以后直接用!
NSString *content = @"qwertyuiqwertyuiqwertyui";
NSString *sub= @"wer";
NSMutableArray *locationArr = [self calculateSubStringCount:content str:sub];
NSMutableAttributedString *attstr = [[NSMutableAttributedString alloc] initWithString:content];
for (int i=0; i<locationArr.count; i++) {
NSNumber *location = locationArr[i];
[attstr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(location.integerValue+i*sub.length, sub.length)];
}
self.label.attributedText = attstr;
- (NSMutableArray*)calculateSubStringCount:(NSString *)content str:(NSString *)tab {
int location = 0;
NSMutableArray *location