0

I have array of strings [apple,mango,banana,kiwi,orange] while the user is typing on textview if the last word is matched to any of the words in the array it should be underlined and have tap gesture added to it . I am using the

         func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { 
let lastword = textviewtext.lastword()//i have last word i have to replace

        if myarray.contains(lastword) {
    //here code for replacing the text and underline it and add tap gesture 
    }

how to do this exapmle - user if typed - " orange apple are good for health " here the orange and apple should be underlined and should have tap enabled with some actions .like alert with "orange tapped" or "apple tapped"

1 Answer 1

1

To underline certain words, you're going to want to use rangeOfString to get an NSRange of the word in your text view and create a new attributed string to apply to the text view. Here's an example:

let at = NSMutableAttributedString(string: textView.text)
words.forEach { word in
    if let range = textView.text.range(of: word) {
        at.addAttribute(NSUnderlineColorAttributeName, value: UIColor.red, range: range)
    }
}

textView.attributedText = at

To recognize when the word is tapped, see this answer.

Sign up to request clarification or add additional context in comments.

3 Comments

how to perform this while user entering the text
@AkashShindhe you would put this code in the method you have already
its not working - Cannot convert value of type 'Range<String.Index>' (aka 'Range<String.CharacterView.Index>') to expected argument type 'NSRange' (aka '_NSRange')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.