Close iOS Keyboard by touching anywhere using Swift(使用 Swift 通过触摸任意位置来关闭 iOS 键盘)
问题描述
我一直在寻找这个,但我似乎找不到它.我知道如何使用 Objective-C
关闭键盘,但我不知道如何使用 Swift
来做到这一点?有人知道吗?
I have been looking all over for this but I can't seem to find it. I know how to dismiss the keyboard using Objective-C
but I have no idea how to do that using Swift
? Does anyone know?
推荐答案
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
中使用此功能,这是完成此任务的另一种方法:
Here is another way to do this task if you are going to use this functionality in multiple 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
中,你所要做的就是调用这个函数:
Now in every UIViewController
, all you have to do is call this function:
override func viewDidLoad() {
super.viewDidLoad()
self.hideKeyboardWhenTappedAround()
}
这个函数作为标准函数包含在我的 repo 中,其中包含很多有用的 Swift 扩展,比如这个,检查一下:https://github.com/goktugyil/EZSwiftExtensions
This function is included as a standard function in my repo which contains a lot of useful Swift Extensions like this one, check it out: https://github.com/goktugyil/EZSwiftExtensions
这篇关于使用 Swift 通过触摸任意位置来关闭 iOS 键盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!