2014-08-31 104 views
0

我试图用代码中的多种颜色来设置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

回答

0

它看起来你有你的钥匙/值对您的字典以错误的方式。您的attributes应如下所示:

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