sonu sonu - 3 years ago 64
iOS Question

textView.typingAttributes not working for prediction

I have a textview which is filled with some default text in blue, now my goal is, whatever edit I make in the text it should come in red color. I'm using

texView.typingAttributes
to achieve this and it works almost well, except if I use prediction or autocorrect starting from any words that are in blue, in this case the predicted or auto corrected word still remains in blue. If I use prediction outside the blue area it works fine. Is there anything else that I should do for prediction? Below is my current code that I use to achieve this.

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {

textView.typingAttributes[NSForegroundColorAttributeName] = UIColor.red

return true
}

Answer Source

For Correction, you need to apply the color attribute property for selected range of the string. It's working now, added the code as below:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {

    textView.typingAttributes[NSForegroundColorAttributeName] = UIColor.red

    let colorAttribute = [NSForegroundColorAttributeName: UIColor.red]
    textView.textStorage.addAttributes(colorAttribute, range: range)

        return true
    }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download