Reputation: 1225
I want to get the word that is currently being typed in a UITextField.
Case 1:
hello there
If the cursor is after the second e (meaning e has just been typed, then the word there should be returned
Case 2:
User deletes o from hello (cursor is after the second l), then the word hell should be returned
I have some code for this but it is returning all text in the UITextField.
postView.textView.delegate = self
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
let text = (textView.text as NSString?)?.replacingCharacters(in: range, with: text)
return true
}
Update 1: I have gone through these similar questions but these didn't work for me.
Get currently typed word in UITextView
Upvotes: 1
Views: 1107
Reputation: 3247
Try with below code, its working at my end.
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
let nsString = textView.text as NSString?
let newString = nsString?.replacingCharacters(in: range, with: text)
let arr = newString?.components(separatedBy: " ")
self.lblWord.text = arr?.last
return true
}
Upvotes: 3