Reputation: 576
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"
Upvotes: 0
Views: 2124
Reputation: 3400
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.
Upvotes: 1