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 to your view controller’s viewDidLoad() function as illustrated below:
I hope it helps, thanks for reading!