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 ios ios

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


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 screenshotenter image description here


this is a swift implementation from @Anoop Vaidya answer,this function detect any word between {|myword|} , color these words in red and remove the special characters, hope this may help someone else:

 func getColoredText(text:String) -> NSMutableAttributedString{    var string:NSMutableAttributedString = NSMutableAttributedString(string: text)    var words:[NSString] = text.componentsSeparatedByString(" ")    for (var word:NSString) in words {        if (word.hasPrefix("{|") && word.hasSuffix("|}")) {            var range:NSRange = (string.string as NSString).rangeOfString(word)            string.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: range)            word = word.stringByReplacingOccurrencesOfString("{|", withString: "")            word = word.stringByReplacingOccurrencesOfString("|}", withString: "")            string.replaceCharactersInRange(range, withString: word)        }    }    return string}

you can use it like this:

self.msgText.attributedText = self.getColoredText("i {|love|} this!")


Modified @fareed's answer for swift 2.0 and this is working (tested in a playground):

func getColoredText(text: String) -> NSMutableAttributedString {    let string:NSMutableAttributedString = NSMutableAttributedString(string: text)    let words:[String] = text.componentsSeparatedByString(" ")    var w = ""    for word in words {        if (word.hasPrefix("{|") && word.hasSuffix("|}")) {            let range:NSRange = (string.string as NSString).rangeOfString(word)            string.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: range)            w = word.stringByReplacingOccurrencesOfString("{|", withString: "")            w = w.stringByReplacingOccurrencesOfString("|}", withString: "")            string.replaceCharactersInRange(range, withString: w)        }    }    return string}getColoredText("i {|love|} this!")