Multiple colors in a UILabel

蓝咒 提交于 2019-12-13 07:36:09

问题


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?


回答1:


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
                          },
                        ];


来源:https://stackoverflow.com/questions/25591379/multiple-colors-in-a-uilabel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!