仅当键盘处于活动状态时,点击背景才能关闭TextField键盘

时间:2018-03-11 04:50:36

标签: swift uitextfield uigesturerecognizer

我一直有一个问题,我设置为十进制键盘的文本字段,因为它的十进制键盘没有返回键,所以我必须点击背景来关闭它。我想只允许它识别键盘是否打开时点击。目前,只要你点击背景,它就能识别它。任何帮助都会非常棒。

 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    self.view.endEditing(true)
    label.text = "tapped"
}

1 个答案:

答案 0 :(得分:0)

您可以添加此扩展程序,它对我有用:

trapframe

然后将此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) } } 放入self.hideKeyboardWhenTappedAround()

viewDidLoad