Search code examples
iosnsattributedstring

iOS how to add different attributes to multiple occurrences of same substring


I want to make an NSAttributedString with different attributes for each of the two occurrences of the same substring.

NSString *text = @"ABC & ABC";
NSString *substring = @"ABC"
NSMutableAttributedString *attStr= [[NSMutableAttributedString alloc] initWithString:text];

NSRange range = [[attStr string] rangeOfString:substring];

I want to set different attributes for each occurrence of the substring using the method
[attStr addAttributes:attributes range:range]. However, no matter how many times I run it, only the first occurrence of substring changes the attributes.

Is there a way to let the addAtributes: know to look for substring whose attributes haven't been set yet?


Solution

  • you can calculate how much time word is repeated.

    NSUInteger count = 0, length = [@"ABC & ABC" length];
        NSRange range = NSMakeRange(0, length);
        while (range.location != NSNotFound) {
            range = [self.dateTime rangeOfString:@"ABC" options:0 range:range];
            if (range.location != NSNotFound) {
                range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
                count++;
            }
        }