iOS - 使用TTTAttributedLabel设置两个颜色文本 [英] iOS - Using TTTAttributedLabel to set two color text
问题描述
我正在创建具有标签的iOS应用。我想设置两种颜色。一个用于第一部分,另一个用于剩余部分。
我在Stack over流程中看到了一些消息, TTTAttributedLabel 能够为文本设置多种颜色。我的文字就像ABC> def。对于ABC,我想设置棕色和def,我想设置白色。
我该怎么设置?
I'm creating iOS app that has a label. I want to set two colors. One for first part and other color for remaining part.
I've seen some messages in Stack over flow that, TTTAttributedLabel has the ability to set more than one color to text. My text will be like "ABC > def". For "ABC", i want to set brown color and for "def", i want to set white color.
How can I set that?
推荐答案
NSString* text = @"ABC > def";
attributedLabel = [[[TTTAttributedLabel alloc] initWithFrame:frame] autorelease];
attributedLabel.numberOfLines = 0;
attributedLabel.lineBreakMode = UILineBreakModeWordWrap;
attributedLabel.fontColor = [UIColor brownColor];
[attributedLabel setText:text afterInheritingLabelAttributesAndConfiguringWithBlock:^(NSMutableAttributedString *mutableAttributedString) {
NSRange whiteRange = [text rangeOfString:@"def"];
if (whiteRange.location != NSNotFound) {
// Core Text APIs use C functions without a direct bridge to UIFont. See Apple's "Core Text Programming Guide" to learn how to configure string attributes.
[mutableAttributedString addAttribute:(NSString *)kCTForegroundColorAttributeName value:(id)[UIColor whiteColor].CGColor range:whiteRange];
}
return mutableAttributedString;
}];
[attributedLabel sizeToFit]; //this may not be needed if the frame provided is large enough
搜索defin您的字符串并将该范围的文本的前景色设置为白色。希望这可以帮助。我昨天才刚刚学会了这个。在试图为自己解决问题时遇到了你的问题。
That searches for "def" in your string and sets the foreground color of the text to white for that range. Hope this helps. I only just learned this yesterday. Came across your question whilst trying to figure it out for myself.
这篇关于iOS - 使用TTTAttributedLabel设置两个颜色文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!