Search code examples
ios5uitextviewcore-textnsattributedstringcatextlayer

iOS 5: Changing foreground color using attributed string in UITextView


This code works well on iOS 6

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:textView.text];

[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:[textView.text rangeOfString:self.searchString options:NSCaseInsensitiveSearch range:searchRange]];

[textView setAttributedText:attributedString];

However NSForegroundColorAttributeName is undefined in iOS 5, so I want the equivalent of the previous code that works in iOS 5.


Solution

  • The equivalent is to use the kCTForegroundColorAttributeName with a CGColorRef for the color.

    See my CoreText introduction here: http://www.cocoanetics.com/2011/01/befriending-core-text/