iOS development traverses the position information of all substrings in the string and changes the color

 The rangeOfString API that we normally use finds the first string that meets the requirements and returns directly. When we want to change the color of all the strings that meet the requirements, it won’t work. Then we find one and intercept it, and we find the last one. Use an array to record all the positions, the idea is very simple, write it down and use it directly later!

 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 *locationArr = [NSMutableArray new];
    NSRange range = [content rangeOfString:tab];
    if (range.location == NSNotFound){
        return locationArr;
    }
    //声明一个临时字符串,记录截取之后的字符串
    NSString * subStr = content;
    while (range.location != NSNotFound) {
        if (location == 0) {
            location += range.location;
        } else {
            location += range.location + tab.length;
        }
        //记录位置
        NSNumber *number = [NSNumber numberWithUnsignedInteger:location];
        [locationArr addObject:number];
        //每次记录之后,把找到的字串截取掉
        subStr = [subStr substringFromIndex:range.location + range.length];
//        NSLog(@"subStr %@",subStr);
        range = [subStr rangeOfString:tab];
//        NSLog(@"rang %@",NSStringFromRange(range));
    }
    return locationArr;
}

All the wer changes in the string are changed to red!

Guess you like

Origin blog.csdn.net/wangletiancsdn/article/details/105434729