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?
Asked
Active
Viewed 1.3k times
8
2 Answers
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
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.

DonnaLea
- 8,643
- 4
- 32
- 32
-
don't forget to return mutableAttributedString at the end of the block. – djibouti33 Mar 14 '13 at 22:05
-
@djibouti33 thanks, don't know how I missed that. Edited the answer to include that now. – DonnaLea Mar 15 '13 at 00:00
-
Any one has solution for Swift? – guru Feb 09 '19 at 11:27
-
@guru I could convert this to Swift, but attributedText property is available on UILabel since iOS 6 https://developer.apple.com/documentation/uikit/uilabel/1620542-attributedtext – DonnaLea Feb 15 '19 at 21:59
6
You could use TTTRegexAttributedLabel available at : https://github.com/kwent/TTTRegexAttributedLabel. (TTTAttributedLabel based but more easier to use with regular expressions)
//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]];

Quentin Rousseau
- 330
- 5
- 13
-
4Thanks for providing the answer. My problem solved by using TTTAttributedLabel. In future, I'll keep in mind to use the library that you suggested. – Satyam Nov 19 '12 at 10:58