我有 UIViewController
和 UITextfield
以及其他几个元素(几个 subview 和按钮)。我想在点击 UITextfield
之外的某处时关闭键盘。
我知道有一个答案Close iOS Keyboard by touching anywhere using Swift ,但是如果用户点击 viewController 的 subview 或按钮,这种方法不起作用。
我可以为每个 subview 和按钮添加类似的 UITapGestureRecognizer
,但是有没有更智能的方法来解决这个问题?
最佳答案
extension UIViewController{
open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
}
此外,如果 UIScrollView 中有元素,也请添加此方法:
extension UIScrollView {
open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.next?.touchesBegan(touches, with: event)
}
}
关于ios - 通过触摸外部关闭 iOS 键盘(更聪明的方式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53391916/