如何制作具有多种颜色的单个UILabel

Ald*_*ila 2 textcolor nsattributedstring uilabel uicolor ios

我想用2种颜色创建一个uilabel.第一种颜色是黑色,另一种颜色是蓝色.

我可以在其中使用多个uilabel,但我想只有一个uilabel.有什么办法可以实现吗?

这应该是输出.

在此输入图像描述

这是我的代码:

UILabel * lblPostContent = [[UILabel alloc] initWithFrame:CGRectMake((ICON_PADDING*1.5), 42, container.frame.size.width-30, 34)];
lblPostContent.numberOfLines =0;
[lblPostContent setFont:[UIFont systemFontOfSize:11]];
[lblPostContent setText:[NSString stringWithFormat:@"I just scored %d points at %@ using the iBowl app", score, LuckyStrikes]];
[container addSubview:lblPostContent];
Run Code Online (Sandbox Code Playgroud)

Ant*_*Dev 10

你应该使用属性......像这样

NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:yourString];
[text addAttribute: NSForegroundColorAttributeName value: [UIColor blackColor] range: NSMakeRange(0, TXTTOBEBLACKLENGTH)];
[text addAttribute: NSForegroundColorAttributeName value: [UIColor blueColor] range: NSMakeRange(TXTTOBEBLACKLENGTH, TXTTOBEBLBLUELENGTH)];
[lblPostContent setAttributedText: text];
Run Code Online (Sandbox Code Playgroud)


Mik*_*ard 5

为了避免必须计算文本部分的长度并生成NSRanges,您可以使用以下方法NSMutableAttributedString从组件NSAttributedString对象组成最终appendAttributedString::

UIColor *normalColor = [UIColor blackColor];
UIColor *highlightColor = [UIColor blueColor];
UIFont *font = [UIFont systemFontOfSize:12.0];        
NSDictionary *normalAttributes = @{NSFontAttributeName:font, NSForegroundColorAttributeName:normalColor};
NSDictionary *highlightAttributes = @{NSFontAttributeName:font, NSForegroundColorAttributeName:highlightColor};

NSAttributedString *normalText = [[NSAttributedString alloc] initWithString:@"Normal " attributes:normalAttributes];
NSAttributedString *highlightedText = [[NSAttributedString alloc] initWithString:@"Highlighted" attributes:highlightAttributes];

NSMutableAttributedString *finalAttributedString = [[NSMutableAttributedString alloc] initWithAttributedString:normalText];
[finalAttributedString appendAttributedString:highlightedText];

self.label.attributedText = finalAttributedString;
Run Code Online (Sandbox Code Playgroud)