简体   繁体   中英

Get the last word that is being typed

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

Get word that is being typed

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM