📜  在 swift 5 外部点击时关闭键盘 - Swift 代码示例

📅  最后修改于: 2022-03-11 15:01:02.344000             🧑  作者: Mango

代码示例1
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)
    }
}

//Now in every UIViewController, all you have to do is call this function:

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