I'm trying to set a UILabel with multiple colours in code. I've made a simple example:
- (void)viewDidLoad {
[super viewDidLoad];
static UIFont *font;
font = [UIFont fontWithName:@"HelveticaNeue-Light" size:10];
NSArray *attributes = @[
@{
[UIColor redColor]: NSForegroundColorAttributeName,
font: NSFontAttributeName
},
@{[UIColor blueColor]: NSForegroundColorAttributeName,
font: NSFontAttributeName},
@{[UIColor greenColor]: NSForegroundColorAttributeName,
font: NSFontAttributeName}
];
NSArray *bits = @[@"aa", @"bb", @"cc"];
NSDictionary *slashAttributes = @{[UIColor grayColor]: NSForegroundColorAttributeName};
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] init];
NSAttributedString *slash = [[NSAttributedString alloc] initWithString:@" / " attributes:slashAttributes];
NSInteger i = 0;
for (NSString *bit in bits) {
NSAttributedString *bitWithAttributes = [[NSAttributedString alloc] initWithString:bit attributes:attributes[i]];
[string appendAttributedString:bitWithAttributes];
[string appendAttributedString:slash];
i++;
};
[self.label setAttributedText:string];
}
On the storyboard I've created the label I want in the top in IB and then the label to change dynamically underneath. The text gets changed but the colors don't. What am I missing?
It looks like you have your keys/values the wrong way round on your dictionaries. Your
attributes
should looks like this: