使用Swift在任何位置触摸可关闭iOS键盘
发布时间:2020-12-14 06:19:05 所属栏目:百科 来源:网络整理
导读:我一直在寻找这一切,但我似乎找不到它。我知道如何使用Objective-C关闭键盘,但我不知道如何使用Swift?有人知道吗? override func viewDidLoad() { super.viewDidLoad() //Looks for single or multiple taps. let tap: UITapGestureRecognizer = UITapGe
我一直在寻找这一切,但我似乎找不到它。我知道如何使用Objective-C关闭键盘,但我不知道如何使用Swift?有人知道吗?
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中使用此功能,这里是另一种方法来执行此任务: // Put this piece of code anywhere you like extension UIViewController { func hideKeyboardWhenTappedAround() { let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self,action: #selector(UIViewController.dismissKeyboard)) view.addGestureRecognizer(tap) } func dismissKeyboard() { view.endEditing(true) } } 现在在每个UIViewController,所有你要做的是调用此函数: override func viewDidLoad() { super.viewDidLoad() self.hideKeyboardWhenTappedAround() } 这个函数作为一个标准函数包含在我的仓库,其中包含了很多有用的Swift扩展,像这样,检查:https://github.com/goktugyil/EZSwiftExtensions (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |