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 键盘


基础教程推荐
- AdMob 广告未在模拟器中显示 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01