Why do you need to dismiss the keyboard?

While developing a new app, I quickly discovered I needed to Dismiss the Keyboard. I was creating the standard setup for an account based app, so Login, Register and Forgot Password screens were needed. Without testing during building my app this would have gone un-noticed. This shows how important it is to test during development of any app.

After placing the UI Text Fields needed and running the iOS simulator, I entered some text into the first Text Field. I soon discovered I could not dismiss the keyboard to continue. Noticing that the keyboard covered the submit button when it opened. I was stuck.

After trying a few different approaches I fixed it. I found a very simple and obvious way on how to approach this. Here is how I did it.

How To Dismiss the keyboard in a View Controller in Swift 3

There are a few ways to dismiss the keyboard and each has it’s benefits. The simplest way I have found is, when you add a Tap Gesture to the View controller. All you have to do is Tap anywhere on the screen, this results in the keyboard being dismissed upon the tap gesture. Below you will find the simple solution I used to implement this.

Simply copy the below code snippit and place it after your viewDidLoad() and boom. What we are doing here is adding an override function. The function gets called when you touch the screen. The function then sets the end editing function to true on the current view. This in turn, dismisses the keyboard.

//Tap gesture function to close keyboard
override func touchesBegan(_ touches: Set, with event: UIEvent?) {

Brian Revie

Brian Revie

A UK Based Web Developer who solves problems for the Business Community

Leave a Reply

This website uses cookies. By continuing to use this site, you accept our use of cookies.