2

I read this question: How to hide keyboard in swift on pressing return key?

and basically there are 2 ways to answer:

  • self.view.endEditing(true)
  • textField.resignFirstResponder()

They both get the job done independently. But do they have any other difference/caveats or places that one one work and the other won't?

Community
  • 1
  • 1
mfaani
  • 33,269
  • 19
  • 164
  • 293

1 Answers1

2

self.view.endEditing(true) is less efficient because it will cycle through the entire view hierarchy and makes sure anything that can be a firstRepsonder has resigned it.

If you know which item is currently the responder, it is more efficient and better practice to call resignFirstResponder on it directly.

random
  • 8,568
  • 12
  • 50
  • 85
  • OK, but if I have multiple textFields like: firstName, LastName, Address, etc. and then at the end I have a **`submit`** button, would doing `self.view.endEditing` be a better choice – mfaani Sep 21 '16 at 18:36
  • 1
    @Honey since not all of those text fields can be the first responder at the same time, when `submit` is selected only one will be the first responder, thus you should call `resignFirstResponder` on it. While I don't think you'll _see_ any performance impact by using `endEditing`, it's generally better "practice" to know which text field is active and only resign on that one. – random Sep 21 '16 at 19:15
  • 1
    It's a really interesting question. I **cannot see any reason** to ever use resignFirstResponder. I believe they will deprecate it in the future. (Regarding the efficiency aspect, you're talking a handful of items, it's irrelevant.) (If for some reason you happen to want to, you can call `endEditing` on just that one item.) – Fattie Jan 21 '17 at 12:58