Chirag Kothiya
Chirag Kothiya

Reputation: 1099

In TTTAttributedLabel two different text color not working

I am using TTTAttributedLabel and set text like "text with #tag and www.example.com".

My need is set redColor for "www.example.com" and greenColor for "#tag".

But it set blue color.

Following is my code:

 [label setText:@"text with #tag and www.example.com" afterInheritingLabelAttributesAndConfiguringWithBlock:^ NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
    NSRange rangeUrl = [[mutableAttributedString string] rangeOfString:@"www.example.com" options:NSCaseInsensitiveSearch];
    NSRange rangeTag = [[mutableAttributedString string] rangeOfString:@"#tag" options:NSCaseInsensitiveSearch];
    UIFont *boldSystemFont = [UIFont systemFontOfSize:IS_IPAD?16:14 weight:UIFontWeightRegular];
    CTFontRef font = CTFontCreateWithName((__bridge CFStringRef)boldSystemFont.fontName, boldSystemFont.pointSize, NULL);
    if (font) {

        [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)font range:rangeUrl];
        [mutableAttributedString addAttribute:(NSString *)kCTForegroundColorAttributeName value:[UIColor redColor] range:rangeUrl];

        [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)font range:rangetag];
        [mutableAttributedString addAttribute:(NSString *)kCTForegroundColorAttributeName value:[UIColor greenColor] range: rangeTag];
        [mutableAttributedString addAttribute:(NSString *)kCTUnderlineColorAttributeName value:[UIColor clearColor] range: rangeTag];

        CFRelease(font);
    }
    return mutableAttributedString;
}];

How to solve this problem.
Please help me!

Upvotes: 0

Views: 532

Answers (1)

Prad M
Prad M

Reputation: 61

You can use this way to change text color of NSMutableAttributedString

NSMutableAttributedString *attributedstring = [[NSMutableAttributedString alloc] initWithString:@"text with #tag and www.example.com"];
attributedstring = [self updateString:attributedstring withChangeColorForText:@"#tag" withColor:[UIColor redColor]];
attributedstring = [self updateString:attributedstring withChangeColorForText:@"www.example.com" withColor:[UIColor greenColor]];

label.attributedText = attributedstring;

updateString Method:

- (NSMutableAttributedString *)updateString:(NSMutableAttributedString *)mainAttributedString withChangeColorForText:(NSString*)searchText withColor:(UIColor*) color

{

NSRange range = [mainAttributedString.string rangeOfString:searchText options:NSCaseInsensitiveSearch];

if (range.location != NSNotFound) {
    [mainAttributedString addAttribute:NSForegroundColorAttributeName value:color range:range];
}

return mainAttributedString;

}

Upvotes: 2

Related Questions