ios - 通过触摸外部关闭 iOS 键盘(更聪明的方式)

标签 ios swift keyboard uitextfield

我有 UIViewControllerUITextfield 以及其他几个元素(几个 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/

相关文章:

ios - Parse.com 云调用算作查询吗?

ios - 您将如何为 CoreData 建模以在 Swift 中保存自定义对象数组?

interface - 键盘隐藏我的 UITableViewController 中的文本字段, View 不滚动

ios - 如果应用程序直接从后台启动而不是从通知消息启动,如何知道推送消息信息?

c# - .NET WebBrowser 控件中的 Javascript keyup/keydown

wordpress - Bootstrap : Carousel with keyboard controls

ios - YouTube 嵌入式播放器在 iOS 8 上因 gpus_ReturnNotPermittedKillClient 而崩溃

ios - Mapbox 导航、iOS SDK 中的重新路由问题

ios - 当我将 Split View Controller 添加到 Storyboard 时,主视图不显示

xcode - Swift 2.0/Xcode 7B5 - 只有放入某个文件中才能找到类