问题
In my current project I discovered that I could add an unwind segue to a UITextField and trigger the segue by pressing the return key if I also added an action to handle the didEndOnExit event. If the didEndOnExit handler is not connected to the event then the segue is not triggered.
I would like to understand this behavior. My interest stems from that there might be something for me to learn about how segues operate. On the other hand, the behavior might just be unique to UITextFields.
This simple GitHub project demonstrates the behavior.
Thank you for your attention.
回答1:
You have done a very unusual thing: you've attached a triggered segue to a text field, as its action segue. So the question is simply: what does that mean? In particular, what triggers a triggered segue attached to a text field? What is the "action" of a text field?
I mean, we know what triggers a triggered segue attached to a button: it's that the user taps the button. And we know what triggers a triggered segue attached to a table view cell: it's that the user selects the cell. But what about a text field? What must the user do to trigger its action segue?
The "unwind" business is a red herring, so let's eliminate it from our thinking. Delete the text field from the second view controller and put it in the first view controller. Hook the text field's action segue as a modal segue to the second view controller.
Now contemplate the text field in the first view controller. It behaves as you have described:
If we click in the text field and type and hit return, nothing happens.
If we add Did End On Exit to the text field and type and hit return, the keyboard is dismissed and we segue.
Well, think about that phrase "nothing happens" in the first bullet point. The keyboard is not dismissed! But dismissal of the keyboard is the text field's "action". There was no action. So there is no triggering of the action segue.
Now try this experiment: make the view controller the text field's delegate, and implement this method:
extension ViewController : UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
Type in the text field and hit Return. The keyboard is dismissed and we segue to the next view controller. Dismissing the keyboard in response the Return key is the text field's action.
So you see, in a sense, both the unwind segue and the DidEndOnExit were red herrings, since I just accomplished the same thing without either of those. What matter is what the text field's Action is, and the triggering of its Action Segue in response.
来源:https://stackoverflow.com/questions/47289747/triggering-a-uitextfield-unwind-segue-by-pressing-return-why-how-does-this-work