ios - 使用 Swift 触摸任意位置关闭 iOS 键盘

标签 ios swift uikeyboard

我一直在寻找这个,但我似乎无法找到它。我知道如何使用 Objective-C 关闭键盘,但我不知道如何使用 Swift 来关闭键盘?有人知道吗?

最佳答案

override func viewDidLoad() {
    super.viewDidLoad()
          
    //Looks for single or multiple taps. 
     let tap = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard))

    //Uncomment the line below if you want the tap not not interfere and cancel other interactions.
    //tap.cancelsTouchesInView = false 

    view.addGestureRecognizer(tap)
}

//Calls this function when the tap is recognized.
@objc func dismissKeyboard() {
    //Causes the view (or one of its embedded text fields) to resign the first responder status.
    view.endEditing(true)
}

如果您要在多个 UIViewControllers 中使用此功能,这是执行此任务的另一种方法:

// Put this piece of code anywhere you like
extension UIViewController {
    func hideKeyboardWhenTappedAround() {
        let tap = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
        tap.cancelsTouchesInView = false            
        view.addGestureRecognizer(tap)
    }
    
    @objc func dismissKeyboard() {
        view.endEditing(true)
    }
}

现在在每个 UIViewController 中,你所要做的就是调用这个函数:

override func viewDidLoad() {
    super.viewDidLoad()
    self.hideKeyboardWhenTappedAround() 
}

此函数作为标准函数包含在我的存储库中,其中包含许多有用的 Swift 扩展,例如这个,查看:https://github.com/goktugyil/EZSwiftExtensions

关于ios - 使用 Swift 触摸任意位置关闭 iOS 键盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24126678/

相关文章:

ios - UIKeyboardBoundsUserInfoKey 已弃用,改用什么?

ios - 运行 AVCaptureDevice.requestAccess 阻塞

Ios 11.2 beta 通用链接打开我的应用程序和 safari

ios - 在 IOS 中查看过渡 [想要更改背景]

ios - 用于去电 iOS webrtc 的 VOIP 拨号器提示音

ios - 当我从一个 View 导航到另一个 View 时,如何让音乐持续播放?

ios - 可选委托(delegate)方法上的 respondsToSelector

swift - 有没有办法在另一个范围内使用我的音乐类型数组?

ios - 防止键盘与 UIButton/UITextField 重叠

ios - 如何检测用户何时更改键盘?