UILabel中的多种颜色

时间:2014-08-31 11:09:19

标签: cocoa-touch uilabel

我试图在代码中设置多种颜色的UILabel。我做了一个简单的例子:

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

在故事板上,我在IB的顶部创建了我想要的标签,然后在下面动态更改标签。文字变了,但颜色没有变化。我错过了什么?

enter image description here

1 个答案:

答案 0 :(得分:0)

看起来你的词典上的键/值是错误的。您的attributes应如下所示:

NSArray *attributes = @[
                        @{
                          NSForegroundColorAttributeName : [UIColor redColor],
                          NSFontAttributeName            : font
                          },
                        @{
                          NSForegroundColorAttributeName : [UIColor blueColor],
                          NSFontAttributeName            : font
                          },
                        @{
                          NSForegroundColorAttributeName : [UIColor greenColor],
                          NSFontAttributeName            : font
                          },
                        ];