I'm looking for a way to color the first word in a sentence in a different color compared to the rest of the sentence. METHOD_001 first colors the entire line in white, and then re-colors the first 8 characters in red. METHOD_002 colors the first 8 characters in red before using the line length to calculate the remaining characters and color them white.
METHOD_001 is by far the best, but I'm curious if there is an easier way, I expected to find NSMutableAttributedString addAttribute:one that did not accept the range, and just applied the attribute to the whole string, it seems a bit oversight that all changes in NSMutableAttributedStringrequire a range to be specified, I missed something ?
NB: The code contains hard-coded values for readability.
NSMutableAttributedString *attrString_001 = [[NSMutableAttributedString alloc] initWithString:@"Distance 1720 mm" attributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
[attrString_001 addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 8)];
[[self nameLabel] setAttributedText:attrString_001];
NSString *string = @"Distance 1720 mm";
NSUInteger stringLength = [string length];
NSMutableAttributedString *attrString_002 = [[NSMutableAttributedString alloc] initWithString:string];
[attrString_002 addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 8)];
[attrString_002 addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(9, (stringLength-9))];
[[self distanceLabel] setAttributedText:attrString_002];
source
share