仅当键盘处于活动状态时,点击背景以关闭 TextField 键盘
Tap background to dismiss TextField keyboard only if keyboard is active
我一直对我设置为十进制键盘的文本字段有问题,因为它的十进制键盘没有 return 键,所以我必须点击背景来关闭它。我只想让它在键盘打开时识别该点击。目前它会在您点击背景时识别它。任何帮助都会非常感谢。
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
label.text = "tapped"
}
你可以添加这个扩展,它对我有用:
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
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
我一直对我设置为十进制键盘的文本字段有问题,因为它的十进制键盘没有 return 键,所以我必须点击背景来关闭它。我只想让它在键盘打开时识别该点击。目前它会在您点击背景时识别它。任何帮助都会非常感谢。
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
label.text = "tapped"
}
你可以添加这个扩展,它对我有用:
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
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}