Best way to dismiss Keyboard in a View Controller iOS (Swift)

Image for post
Image for post

[Updated on 2 Nov 2020]

I was thinking to write about all possible ways to dismiss the keyboard in iOS app and let people figure out which one is best suited one.

UITextFields has keyboard as first responders, as soon you begin editing keyboard shows up. It is developer’s responsibility to write code to dismiss it.
I will try to explain few methods how to do it especially when there are multiple UITextFields on your view controller.

Image for post
Image for post

First way: Implement UITextFieldDelegate’s textFieldShouldReturn method and dismiss current keyboard.

Image for post
Image for post

this solution seems good enough but not all keyboards have return button.

Second way: when textfield has no return keys eg. (UIKeyboardType.numberPad)

Image for post
Image for post

the work around could be adding UIToolbar on top and set a target method

Image for post
Image for post

Third: what could be better than tapping anywhere on the view controller to dismiss the keyboard. Just one line of code would serve our purpose. Add a tap gesture recogniser on self.view, set target as self.view and set selector as endEditing: (in ViewDidLoad() or anywhere you like)

Image for post
Image for post

thats it?

Caveat*: there could be issues if you are dealing with tableviews and adding this tap gesture, selecting the rows, didSelectRowAtIndex path could not be fired until pressed long.

Solution for that is to modify above code as below.

Image for post
Image for post

Just make sure cancelsTouchesInView is set false.

Fourth: If your textfields are added on UIScrollview or any subview of it eg. UITableView, you can use set `keyboard dismiss mode` like below.

this will do all stuff for you without writing any extra code

Image for post
Image for post

Additional:
As Jeff Scaturro has pointed out another cool way to do it. Override the touchesBegan function of viewController and call endEditing on self.view

Image for post
Image for post

And from Subhajit Paul’s suggestion you can do same using global call.

Image for post
Image for post

*Please suggest if you have any more ways to do this.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store