Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

resignFirstResponder vs. endEditing for Keyboard Dismissal

In Swift, both [someTextField].resignFirstResponder() and self.view.endEditing(true) accomplish the same task - hiding the keyboard from the user's view and de-focusing whatever text field was using it. I understand that the former is specific to a particular field, while the latter encompasses the entire view, but other than wanting to target a specific text field, when is one preferred/recommended over the other?

like image 962
curiouslychris Avatar asked Apr 26 '15 19:04

curiouslychris


People also ask

How do you dismiss a keyboard in Swift?

Via Tap Gesture This is the quickest way to implement keyboard dismissal. Just set a Tap gesture on the main View and hook that gesture with a function which calls view. endEditing . Causes the view (or one of its embedded text fields) to resign the first responder status.

What is resignFirstResponder Swift?

resignFirstResponder()Notifies this object that it has been asked to relinquish its status as first responder in its window.


1 Answers

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.

like image 157
nhgrif Avatar answered Sep 21 '22 11:09

nhgrif