Software, Tech & Coding simplified.

Swift How to Make Keyboard Disappear Touching Anywhere

Dismiss keyboard in Swift

In Swift 5, you can hide the keyboard by touching anywhere on the screen with these two lines of code:

 let tapGesture = UITapGestureRecognizer(target: view, action: #selector(UIView.endEditing))
 view.addGestureRecognizer(tapGesture)

This code adds a tap gesture recognizer into the current view that listens for actions that suggest that the user stopped editing the text field/text view.

To make this code work, add it into your view controller’s viewDidLoad() function as illustrated below:

How to hide keyboard in Swift by tapping anywhere in the screen

I hope it helps, thanks for reading!

Further Reading

50 Swift Interview Questions

Share

Share on twitter
Share on linkedin
Share on facebook
Share on pinterest
Share on email