Search code examples
ioscocoa-touchtextuicolorhashtag

UITextView attributed colour not being applied - iOS


I have a UITextView which displays tweets. Some tweets have hashtags. I found a great answer on StackOverflow which allows me to identify the hashtag and then apply a colour to it. However the attributedText property of my UITextView is not being applied.... for some reason. Here is my code:

NSString *message = final_data[index];
NSArray *words = [message componentsSeparatedByString:@" "];
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:message];
            
            for (NSString *word in words) {
                
                if ([word hasPrefix:@"#"]) {
                    
                    NSRange matchRange = [message rangeOfString:word];
                    [attrString addAttribute:(__bridge NSString *)kCTForegroundColorAttributeName value:[UIColor blueColor] range:matchRange];
                }
            }
            
            cell_tw.message_post.attributedText = attrString;

"message_post" is my UITextView in my Custom Cell in my UITableview.

I though the whole point of the attributedText property is so you can set these kinds of settings such as text colour.

What is going wrong here?


Solution

  • Have you tried this?

    [attrString setAttributes:[NSDictionary dictionaryWithObject:[UIColor blueColor] forKey:NSForegroundColorAttributeName] range:[message rangeOfString:word]];