2012-03-01 24 views
8

我正在创建具有标签的iOS应用程序。我想设置两种颜色。第一部分为其余部分,其余部分为其他颜色。
我已经看到Stack over flow中的一些消息,TTTAttributedLabel能够将多个颜色设置为文本。我的文本将会像“ABC> def”一样。对于“ABC”,我想设置棕色和“def”,我想设置白色。
我该如何设置?iOS - 使用TTTAttributedLabel设置两种颜色文本

回答

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”并将文本的前景色设置为该范围的白色。希望这可以帮助。我昨天才知道这件事。遇到你的问题,同时试图找出自己。

+0

不要忘记在块的结尾处返回mutableAttributedString。 – djibouti33 2013-03-14 22:05:25

+0

@ djibouti33谢谢,不知道我是如何错过了。编辑答案包括现在。 – DonnaLea 2013-03-15 00:00:17

6

您可以使用TTTRegexAttributedLabel:https://github.com/kwent/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]]; 
+4

感谢您提供答案。我的问题通过使用TTTAttributedLabel解决。将来,我会记住使用您建议的库。 – Satyam 2012-11-19 10:58:34