在搜索栏外部单击时使键盘消失-SWIFT

时间:2018-08-25 16:04:29

标签: ios swift searchbar

我有一个UIViewController,并且嵌入了一个搜索栏和一个集合视图。当我按搜索栏时,出现键盘。如果用户决定通过点击屏幕上除搜索栏之外的任何位置来改变主意,我希望隐藏此键盘。我尝试了以下方法但没有成功:

  1. 添加敲击手势识别器
  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)
     }
    
    }
    

enter image description here

1 个答案:

答案 0 :(得分:4)

您可以使用此扩展名。

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