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 键盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Swift 通过触摸任意位置来关闭 iOS 键盘


基础教程推荐
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01