Nithin M Keloth Nithin M Keloth - 10 days ago 4
iOS Question

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

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

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

Comments