I\'m trying to make a \"tagging window\" much like the one used in Facebook where you type \"@\" and it make suggestions among your friends on which one to tag. I\'d like th
Swift 4:
This solution worked for me inside the method func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool
of UITextViewDelegate.
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
guard let textFieldText = textView.text,
let rangeOfTextToReplace = Range(range, in: textFieldText) else {
return false
}
let currentText = textFieldText.replacingCharacters(in: rangeOfTextToReplace, with: text)
return count <= 150
}
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
}
}
As usual I spent a fair amount of time trying to get this to work, and minutes after I posted the question I got it working. So here's the code I used, but I have deprecated call for the let 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
}