使用Swift触摸任何地方关闭iOS键盘 [英] Close iOS Keyboard by touching anywhere using Swift
问题描述
我一直在寻找这个,但我似乎无法找到它。我知道如何使用 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 = UITapGestureRecognizer(target: self, action: "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.
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 = 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()
}
这个功能on包含在我的repo中的标准函数中,其中包含许多有用的Swift Extensions,请查看: 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键盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!