Cocoa touch 标签中的多种颜色
我正在尝试在代码中设置具有多种颜色的UILabel。我举了一个简单的例子:Cocoa touch 标签中的多种颜色,cocoa-touch,uilabel,Cocoa Touch,Uilabel,我正在尝试在代码中设置具有多种颜色的UILabel。我举了一个简单的例子: - (void)viewDidLoad { [super viewDidLoad]; static UIFont *font; font = [UIFont fontWithName:@"HelveticaNeue-Light" size:10]; NSArray *attributes = @[ @{
- (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的顶部创建了我想要的标签,然后在下面动态更改标签。文本会更改,但颜色不会更改。我错过了什么
看起来您的字典中的键/值出现了错误。您的
属性应如下所示:
NSArray *attributes = @[
@{
NSForegroundColorAttributeName : [UIColor redColor],
NSFontAttributeName : font
},
@{
NSForegroundColorAttributeName : [UIColor blueColor],
NSFontAttributeName : font
},
@{
NSForegroundColorAttributeName : [UIColor greenColor],
NSFontAttributeName : font
},
];