Is it possible to change color of single word in UITextView and UITextField

Nithin M Keloth picture Nithin M Keloth · Jan 9, 2013 · Viewed 27.3k times · Source

Is it possible to change color of single word in UITextView and UITextField ?

If i have typed a word with a symbol infront (eg: @word) , can it's color be changed ?

Answer

Anoop Vaidya picture Anoop Vaidya · Jan 9, 2013

Yes you need to use NSAttributedString for that, find the RunningAppHere.

Scan through the word and find the range of your word and change its color.

EDIT:

- (IBAction)colorWord:(id)sender {
    NSMutableAttributedString * string = [[NSMutableAttributedString alloc]initWithString:self.text.text];

    NSArray *words=[self.text.text componentsSeparatedByString:@" "];

    for (NSString *word in words) {        
        if ([word hasPrefix:@"@"]) {
            NSRange range=[self.text.text rangeOfString:word];
            [string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];           
        }
    }
    [self.text setAttributedText:string];
}

EDIT 2 : see the screenshot enter image description here