问题
I have a UIViewController and I have embedded a Search Bar and a Collection View. When I press on the searchbar, the keyboard appears. I would like to hide this keyboard if the user decides to change his mind by tapping any where on the screen but the search bar. I have tried the following without success:
- Adding a Tap Gesture Recognizer
using 'self.mySearchBar.endEditing(true)'
class CollectionViewFolder: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate ,UICollectionViewDelegateFlowLayout, UISearchBarDelegate{ /*** OUTLETS ***/ @IBOutlet weak var mySearchBar: UISearchBar! // 1. I have tried adding a Tap Gesture Recognizer // TAP ON SCREEN LISTENER @IBAction func tapOnScreen(_ sender: UITapGestureRecognizer) { print("tap tap ...") self.mySearchBar.resignFirstResponder() } // 2. Added the following to the viewDidLoad: override func viewDidLoad() { super.viewDidLoad() self.mySearchBar.endEditing(true) } }
回答1:
You can use this extension.
extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
@objc func dismissKeyboard() {
view.endEditing(true)
}
}
Usage. In your viewController:
override func viewDidLoad() {
super.viewDidLoad()
hideKeyboardWhenTappedAround()
}
来源:https://stackoverflow.com/questions/52019014/make-keyboard-disappear-when-clicking-outside-of-search-bar-swift