Member-only story

Hide a keyboard by tapping the background — Swift 5 basics

Even in a UIScrollView()?

Steven Curtis
2 min readOct 30, 2019

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

Prerequisites:

  • You just need to know what the keyboard is, a view and iOS

Terminology

Tap: A UITapGestureRecognizer allows you to detect when the user taps the screen

Implementation

A gesture recognizer within the ViewController

We can add a gesture recognizer, and resignFirstResponder from each TextField (or other control)

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):

--

--

No responses yet