Multiple colors in a UILabel

2019-08-20 07:54发布

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?

enter image description here

1条回答
戒情不戒烟
2楼-- · 2019-08-20 08:49

It looks like you have your keys/values the wrong way round on your dictionaries. Your attributes should looks like this:

NSArray *attributes = @[
                        @{
                          NSForegroundColorAttributeName : [UIColor redColor],
                          NSFontAttributeName            : font
                          },
                        @{
                          NSForegroundColorAttributeName : [UIColor blueColor],
                          NSFontAttributeName            : font
                          },
                        @{
                          NSForegroundColorAttributeName : [UIColor greenColor],
                          NSFontAttributeName            : font
                          },
                        ];
查看更多
登录 后发表回答