Search code examples
iosobjective-cnsattributedstring

Two Colors NSMutableAttributeString


Currently I am coloring the world "liked" in my UILabel.

I would like to know how to color everything else that appears in the label. Currently struggling with this capability as ranges always change.

NSMutableAttributedString *mutableString = nil;
NSString *notificationText = [NSString stringWithFormat:@"%@ liked your Recap.", [[object objectForKey:@"from"] valueForKey:@"name"]];
mutableString = [[NSMutableAttributedString alloc] initWithString:notificationText];

NSString *pattern = @"(liked)";
NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];

NSRange range = NSMakeRange(0,[notificationText length]);

[expression enumerateMatchesInString:notificationText options:0 range:range usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
    NSRange finalRange = [result rangeAtIndex:1];
    [mutableString addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:finalRange];
    cell.notificationUser.attributedText = mutableString;
    cell.notificationUser.font = RobotoMedium(15.0f);
    cell.notificationTime.font = RobotoRegular(14.0f);
}];

Solution

  • As @rmaddy pointed out, you can set the color of the entire string first and then change the specific range next like this:

    [mutableString addAttribute:NSForegroundColorAttributeName
                          value:[NSColor blueColor]
                          range:NSMakeRange(0, [mutableString length])];
    
    [mutableString addAttribute:NSForegroundColorAttributeName 
                          value:[UIColor orangeColor] 
                          range:finalRange];