2014-08-31 144 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 
          }, 
         ];