Get currently entered word in UITextView
I'm trying to make a "tag box" just like the one used on Facebook, where you type "@" and make suggestions among your friends to tag. I need this feature in my application, but I can't figure out for the rest of my life how to get the currently entered word in order to filter sentences.
I am using UITextView
, and I was looking at this post on StackOverflow question.
but I have problems translating this to Swift 3 and even so the comments show that this is still not resolved.
So, the functionality I'm using is:
- The user starts typing
UITextView
, and if the word starts with "@" I would like to extract the word. - I would like to replace the word and with a specific input. Let's say the user is using @abc and I filter out the sentence that says " abcdef " and then I want to replace @abc in the UITextView with " abcdef ".
Note that I want the word currently being printed and not the last word entered.
source to share
This works for me.
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
}
}
source to share
As usual, I spent quite a bit of time trying to get this to work, and a few minutes after I posted the question, I got it working. So here is the code I used, but I have a legacy call forlet myRange
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
let myRange = Range<String.Index>(start: textView.text.startIndex, end: textView.text.startIndex.advancedBy(range.location))
var subString = textView.text.substringWithRange(myRange)
subString += text
let wordArray = subString.componentsSeparatedByString(" ")
if let wordTyped = wordArray.last {
currentWord = wordTyped
print("word typed: " + wordTyped)
}
return true
}
source to share