点击任意位置隐藏键盘

给view加一个点击事件,点击时收起键盘:

    override func viewDidLoad() {
        super.viewDidLoad()

        let tap = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard))
        tap.cancelsTouchesInView = false
        self.view.addGestureRecognizer(tap)
    }

    @objc func dismissKeyboard() {
        self.view.endEditing(true)
    }

open var cancelsTouchesInView: Bool // default is YES. causes touchesCancelled:withEvent: or pressesCancelled:withEvent: to be sent to the view for all touches or presses recognized as part of this gesture immediately before the action method is called.

如果不加tap.cancelsTouchesInView = false这一句,view中其他的点击事件会失效,例如tableview的didSelectRow。

原文地址:https://www.cnblogs.com/argenbarbie/p/12513759.html