我一直在到处找这个,但我似乎找不到。我知道如何解雇使用Objective-C键盘,但我不知道如何使用Swift?有人知道吗?


当前回答

你可以使用swift

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesBegan(touches, with: event)
    view.endEditing(true)

}

其他回答

我得到了你

override func viewDidLoad() {
    super.viewDidLoad() /*This ensures that our view loaded*/
    self.textField.delegate = self /*we select our text field that we want*/   
    self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("dismissKeyboard")))
}

func dismissKeyboard(){ /*this is a void function*/
    textField.resignFirstResponder() /*This will dismiss our keyboard on tap*/
}
override func viewDidLoad() {
        super.viewDidLoad()

self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tap)))

}

func tap(sender: UITapGestureRecognizer){
        print("tapped")
        view.endEditing(true)
}

试试这个,很管用

斯威夫特3:

扩展选择器作为参数,能够做额外的东西在解散函数和cancelsTouchesInView,以防止扭曲与触摸的其他元素的视图。

extension UIViewController {
    func hideKeyboardOnTap(_ selector: Selector) {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: selector)
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }
}

用法:

override func viewDidLoad() {
    super.viewDidLoad()
    self.hideKeyboardOnTap(#selector(self.dismissKeyboard))
}

func dismissKeyboard() {
    view.endEditing(true)
    // do aditional stuff
}

你可以打电话

resignFirstResponder()

在UIResponder的任何实例上,例如UITextField。如果你在当前导致键盘显示的视图上调用它,那么键盘将会消失。

这一行代码辞去了UIView中所有UITextField的键盘

self.view.endEditing(true)