Make keyboard disappear when clicking outside of Search Bar - SWIFT

独自空忆成欢 提交于 2019-12-23 02:52:39

问题


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:

  1. Adding a Tap Gesture Recognizer
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!