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:

I hope it helps, thanks for reading!
Further Reading
About the Author
- I'm an entrepreneur and a blogger from Finland. My goal is to make coding and tech easier for you with comprehensive guides and reviews.
Recent Posts
Artificial Intelligence2023.03.14Best AI Tools of 2023 (Save Time & Boost Productivity)
Python2023.02.16How to Pass a Variable from HTML Page to Another (w/ JavaScript)
JavaScript2023.02.16JavaScript How to Get Selected Text from a Textbox
JavaScript2023.02.15JavaScript Select All Text in Div with a Mouse Click