我一直在寻找这个,但我似乎无法找到它。我知道如何使用 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/