Hide a keyboard by tapping the background — Swift 5 basics

Even in a UIScrollView()?

Image for post
Image for post

You might want to hide a keyboard by tapping in the background of a view. In fact you are extremely likely to want to do this at some point in creating




A gesture recognizer within the ViewController

The function needs to be an @objc func as the instance method needs to be exposed to Objective-C

This is called by adding the tag-gesture (which can be added in ViewDidLoad(), or another appropriate point):


We would need to have this in every appropriate ViewController, and add *.resignFirstResponder() for many controls on the page. We really need a reusable way of doing this.

A UIViewController extension

I’ve called this file UIViewController — hideKeyboardOnBackgroundTouched.swift and placed it in a folder called extensions within my project.

This can then be called from within any ViewController with the following:

Why it matters

This is certainly something that you want.

Make it happen.

A clap is gratefully received, a follow likewise:

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