Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying entire NSMutableAttributedString using addAttribute:

I am looking for a way to color the first word in a sentence a different color to that of the rest of the sentence. METHOD_001 first colors the whole string white then re-colors the first 8 characters red. METHOD_002 colors the first 8 characters red, before using the string length to calculate the remaining characters and color them white.

METHOD_001 is definitely the best, but I am curious if there is a simpler way, I was expecting to find a NSMutableAttributedString addAttribute: that did not take a range and just applied the attribute to the whole string, it seems a bit of an oversight that all modifications to a NSMutableAttributedString require you to specify a range, am I missing something?

NB: Code includes hard coded values to aid 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];
like image 722
fuzzygoat Avatar asked Apr 10 '13 16:04

fuzzygoat


1 Answers

Actually there is quite an easy way to do that. Even if you set an attributed text to your label, first it is stylized by the regular properties of the label, it is then your attributed string overrides corresponding ones. So if you do [distanceLabel setTextColor:[UIColor whiteColor]] beforehand (in storyboard or code) you can recolor only the needed parts by using attr. strings and achieve your desired effect.

like image 113
guenis Avatar answered Oct 04 '22 15:10

guenis