resignFirstResponder vs. endEditing for Keyboard Dismissal

后端 未结 2 1653
借酒劲吻你
借酒劲吻你 2020-12-08 00:02

In Swift, both [someTextField].resignFirstResponder() and self.view.endEditing(true) accomplish the same task - hiding the keyboard from the user\'

相关标签:
2条回答
  • 2020-12-08 00:26

    There is no such strict rule.

    You use resignFirstResponder when you have the reference of the text field currently holding first responder status. When you don't have the reference or you are unsure about that, endEditing would do the trick.

    One thing however should be noted that endEditing has a boolean parameter that we occasionally set to true. By setting this parameter to true the view, on which endEditing has been called, will force every child text field to resign first responder status irrespective of it has returned a false value from textFieldShouldEndEditing delegate method. On the contrary calling endEditing with false would only ask (not force) the text field to resign, respecting the return value from textFieldShouldEndEditing protocol method.

    0 讨论(0)
  • 2020-12-08 00:47

    someTextField.resignFirstResponder()

    resignFirstResponder() is good to use any time you know exactly which text field is the first responder and you want to resign its first responder status. This can be slightly more efficient then the alternative, but if you're doing something such as creating a custom control, this can make plenty of sense. Perhaps you have a text field, and when the "Next" button is pressed, you want to get rid of the keyboard and present a date picker, for example. Here, I would definitely use resignFirstResponder()

    self.view.endEditing(true)

    I typically reserve this for scenarios when I just absolutely need to clear the keyboard no matter what is currently going on, for whatever reason. Perhaps, I've got a slide-over menu? Just before this slides out, no matter what is going on, the keyboard should go away, so I'll make sure everything resigns its first responder status. It's important to note that endEditing() will look through the entire hierarchy of subviews and make sure whatever is the first responder resigns its status. This makes it less efficient then calling resignFirstResponder() if you already have a concrete reference to the first responder, but if not, it's easier than finding that view and having it resign.

    0 讨论(0)
提交回复
热议问题