UITextField not calling editingChanged event when text is autocorrected

Viewed 735

I have a UITextField with a return key type of Done, and I've set the delegate to resign first responder status when the return button is tapped. I've also set an editingChanged action to let me know when the user edits the text. But it seems like it isn't being called in the following context.

Say the user has entered "Pizzs" into the text field. The editingChanged action is triggered and it says the text field's value is "Pizzs". Meanwhile, "Pizza" comes up as a suggestion in the keyboard suggestion bar. If they hit the space bar, the autocorrection is accepted and the editingChanged event is called, with the new text "Pizza ". But if they hit Done then the keyboard is dismissed, the text is changed to "Pizza" in the UITextField, but editingChanged is never called.

This is a bug, right? Should I report it to Apple? Or is this expected behavior because the text is being changed programmatically rather than by the user? And can anyone think of a good workaround?

2 Answers

You should use .allEditingEvents for this case.

textField.addTarget(self, action: #selector(didChangeText(_:)), for: .allEditingEvents)

I had the same issue, and worked around it by implementing the UITextFieldDelegate method textFieldShouldReturn(_ textField: UITextField) -> Bool, and doing the same thing there that I was doing in my editingChanged event handler.

So, I basically did this:

textField.addTarget(self, action: #selector(textFieldEditingChanged(_:)), for: .editingChanged)

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    processText()
    return false
}

@objc func textFieldEditingChanged(_ textField: UITextField) {
    processText()
}

func processText() {
    // Process text here
}
Related