且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

UITextView归因颜色未应用 - iOS

更新时间:2023-01-02 20:20:15


$ b
  [attrString setAttributes:[NSDictionary dictionaryWithObject:[UIColor blueColor] forKey:NSForegroundColorAttributeName] range:[message rangeOfString :字]]; 

谢谢!


I have a UITextView which displays tweets. Some tweets have hashtags. I found a great answer on *** 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?

Thanks for you're time :)

have you tried this?

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

Thanks!