在搜索栏外部单击时,键盘会消失 – SWIFT

我有一个UIViewController,我嵌入了一个搜索栏和一个集合视图。 当我按下搜索栏时,会出现键盘。 如果用户决定通过点击屏幕上的任何位置而不是搜索栏来改变主意,我想隐藏此键盘。 我试过以下但没有成功:

  1. 添加Tap手势识别器
  2. 使用’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) } } 

在此处输入图像描述

您可以使用此扩展程序。

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

用法。 在你的viewController中:

 override func viewDidLoad() { super.viewDidLoad() hideKeyboardWhenTappedAround() }