Dismissing the keyboard in a UIScrollView

后端 未结 12 2308
醉话见心
醉话见心 2020-11-30 20:18

Alright, I have a couple of UITextFields and UITextViews inside a UIScrollView, and I\'d like to set the keyboard to disappear wheneve

12条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 20:55

    Create a extension class for hiding keyboard when touches scrollview/view anywhere

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

    }

    And call this method in viewDidLoad like

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

提交回复
热议问题