I have been working on this for a long time now. I have read articles from Get currently typed word in UITextView and Get currently typed word in a UITextView and I think I am very close. My problem is that after I am able to successfully detect the '@' symbol, for some reason the word that should be returned is not getting returned. For example:
func textViewDidChange(_ textView: UITextView) {
commentString = commentTextView.text
commentTextView.setTextTyping(text: commentTextView.text, withHashtagColor: .blue, andMentionColor: .red, andCallBack: callBack, normalFont: UIFont(name: "HelveticaNeue", size: 14)!, hashTagFont: UIFont(name: "HelveticaNeue-Medium", size: 14)!, mentionFont: UIFont(name: "HelveticaNeue-Medium", size: 14)!)
if let word = textView.currentWord {
if word.hasPrefix("@") {
print(word)
print(users)
print("Observing")
}
}
}
I am able to detect the "@" however, after the boolean test of .hasPrefix, the word that should follow is not being printed to the console. If I print 'word' prior to the boolean test then the correct word is printed to the console. This is the extension I am using to detect the "@" symbol.
extension UITextView {
var currentWord : String? {
let beginning = beginningOfDocument
if let start = position(from: beginning, offset: selectedRange.location),
let end = position(from: start, offset: selectedRange.length) {
let textRange = tokenizer.rangeEnclosingPosition(end, with: .word, inDirection: 1)
if let textRange = textRange {
return text(in: textRange)
}
}
return nil
}
}
Any help is appreciated in advance, Thanks!