0

My UIViewController confirms to UITextFieldDelegate and implements delegate method:

func textFieldDidEndEditing(_ textField: UITextField)

It also sets delegate = self in viewDidLoad All works fine when user enters text from keyboard. However, the above delegate method is not called when I set text programatically. i.e textField.text = "some text"

I have also tried calling textField.sendActions(for: .editingDidEnd). Please note that I need to trigger this delegate method while writing unit tests for my controller.

3
  • 1
    This method is called after the text field resigns its first responder status.Setting the text property in code does not change the status of the first responder. Commented Aug 15, 2021 at 19:13
  • 3
    All this does is describe the (correct) behavior. What's the question? Commented Aug 15, 2021 at 19:19
  • To be specific, question is that why textField.sendActions(for: .editingDidEnd) method is not causing to trigger the delegate method "func textFieldDidEndEditing(_ textField: UITextField)" Commented Aug 16, 2021 at 18:21

2 Answers 2

1

Delegate methods respond to user input only. you need to manually call the delegate methods after setting the text.

Sign up to request clarification or add additional context in comments.

Comments

0

From Apple documentation for textFieldDidEndEditing:

"This method is called after the text field resigns its first responder status."

You are changing the value of textField, not resigning it.

You could add an observer for textDidChangeNotification, which will notify you when text value is changed. Refer to point 4

1 Comment

I want the delegate method to be triggered "func textFieldDidEndEditing(_ textField: UITextField)", when text is set programatically. How can i forcibly trigger that?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.