触摸另一个控件(如按钮)Swift 2.0时如何隐藏键盘

问题描述 投票:0回答:3

我已经阅读了这个页面:Close iOS Keyboard by touching anywhere using Swift了解如何隐藏键盘,当我触摸视图时它很好,但当我触摸按钮时它不起作用,有人知道吗?

keyboard swift2 hide
3个回答
2
投票

将其粘贴到您的控制器中:

let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(YourViewController.dissmissKeyboard))
    view.addGestureRecognizer(tap)

 @objc func dissmissKeyboard() {
    view.endEditing(true)

}

0
投票

这是一个黑客,但它工作得很好,键盘甚至隐藏在背景上。我不确定按钮是否能解决您的问题,但请试一试!

编辑:尝试将UITapGestureRecognizer添加到您的按钮?

在viewDidLoad中添加代码:

self.hideKeyboardWhenTappedAround()

然后为ViewController添加一个扩展:

extension UIViewController {
func hideKeyboardWhenTappedAround() {
    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
    view.addGestureRecognizer(tap)
}

func dismissKeyboard() {
    view.endEditing(true)
}
}

对我来说真的很好用。


0
投票

SWIFT 4

将其添加到viewDidLoad。

 let endEditingTapGesture = UITapGestureRecognizer(target: view, action: #selector(UIView.endEditing(_:)))
        endEditingTapGesture.cancelsTouchesInView = false
        view.addGestureRecognizer(endEditingTapGesture)
© www.soinside.com 2019 - 2024. All rights reserved.