我正在创建具有标签的iOS应用。我想设置两种颜色。一个用于第一部分,另一个用于剩余部分 我在Stack over flow中看到了一些消息,TTTAttributedLabel能够为文本设置多种颜色。我的文字就像“ABC> def”。对于“ABC”,我想设置棕色和“def”,我想设置白色 我该怎么设置呢?
答案 0 :(得分:16)
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
在字符串中搜索“def”,并将该范围内文本的前景色设置为白色。希望这可以帮助。我昨天才刚刚学会了这个。在试图为自己解决问题时遇到了你的问题。
答案 1 :(得分:6)
您可以在https://github.com/kwent/TTTRegexAttributedLabel使用TTTRegexAttributedLabel。 (基于TTTAttributedLabel,但更容易使用正则表达式)
//SET FONT ONLY ON FIRST MATCH REGEX
TTTRegexAttributedLabel *label = [[TTTRegexAttributedLabel alloc] init];
label.textColor = [UIColor whiteColor];
NSString *s = @"ABC > def";
[self.label setText:s withFirstMatchRegex:@"^[a-zA-Z ]*>"
withFont:[UIFont systemFontOfSize:12]
withColor:[UIColor brownColor]];