Modifying the entire NSMutableAttributedString using addAttribute:

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.

// METHOD_001
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];

// METHOD_002
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];
+5
source share
1 answer

There is actually a fairly simple way to do this. Even if you set the attribute text to your label, it is first styled according to the usual label properties, and then your attribute string overrides the corresponding ones. Therefore, if you do it [distanceLabel setTextColor:[UIColor whiteColor]]in advance (in a storyboard or code), you can repaint only the necessary parts using attr. and achieve the desired effect.

+5
source

All Articles