UILabel中的多种颜色 [英] Multiple colors in a UILabel
本文介绍了UILabel中的多种颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在代码中设置具有多种颜色的UILabel。我举了一个简单的例子:
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];
}
在故事板上,我在IB的顶部创建了想要的标签然后标签在下面动态更改。文字被更改,但颜色未更改。我丢失了什么?
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?
推荐答案
看起来您的键/值在字典上的输入方式错误。您的属性
应该看起来像这样:
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
},
];
这篇关于UILabel中的多种颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文