2012-03-01 23 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