I have a text label inside a UITableViewCell
consisting of two words.
How can I change the color of the words; making the first word green, and the second word red?
I have a text label inside a UITableViewCell
consisting of two words.
How can I change the color of the words; making the first word green, and the second word red?
NSString *twoWords = @"Green Red";
NSArray *components = [twoWords componentsSeparatedByString:@" "];
NSRange greenRange = [twoWords rangeOfString:[components objectAtIndex:0]];
NSRange redRange = [twoWords rangeOfString:[components objectAtIndex:1]];
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:twoWords];
[attrString beginEditing];
[attrString addAttribute: NSForegroundColorAttributeName
value:[UIColor greenColor]
range:greenRange];
[attrString addAttribute: NSForegroundColorAttributeName
value:[UIColor redColor]
range:greenRange];
[attrString endEditing];
Then you can use attrString directly on a UILabel (> iOS 6, check Apple Documentation).
The simplest way to do this would be with an nsattributedstring in iOS 6.0 or later. You would allocate one of those and in the titleLabel
(or any other object that holds text) of the UITableViewCell
. If you're using the titleLabel
you would do this:
[cell.titleLabel setAttributedText:yourAttributedString];
To setup the colors with an NSAttributedString
, do this:
NSMutableAttributedString* attributedString = [[NSMutableAttributedString alloc] initWithString:stringToManipulate];
[attributedString beginEditing];
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(0, widthOfFisrtWord)];
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(widthOfFisrtWord, widthOfSecondWord)];
[attributedString endEditing];
Note that the ranges provided above using NSMakeRange
won't be the ranges you need. You'll have to change the range to fit your own needs depending if the two words have a space in between them or other characters.
Apple Documentation:
This question addresses getting part of a string, which you would need to do. Instead of modifying the text with BOLD though, you can use this question to get an idea of how to change the color.