使用Swift在任何位置触摸可关闭iOS键盘

前端之家收集整理的这篇文章主要介绍了使用Swift在任何位置触摸可关闭iOS键盘前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我一直在寻找这一切,但我似乎找不到它。我知道如何使用Objective-C关闭键盘,但我不知道如何使用Swift?有人知道吗?
  1. override func viewDidLoad() {
  2. super.viewDidLoad()
  3.  
  4. //Looks for single or multiple taps.
  5. let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self,action: "dismissKeyboard")
  6.  
  7. //Uncomment the line below if you want the tap not not interfere and cancel other interactions.
  8. //tap.cancelsTouchesInView = false
  9.  
  10. view.addGestureRecognizer(tap)
  11. }
  12.  
  13. //Calls this function when the tap is recognized.
  14. func dismissKeyboard() {
  15. //Causes the view (or one of its embedded text fields) to resign the first responder status.
  16. view.endEditing(true)
  17. }

================================================== ======================

编辑:如果要在多个UIViewControllers中使用此功能,这里是另一种方法来执行此任务:

  1. // Put this piece of code anywhere you like
  2. extension UIViewController {
  3. func hideKeyboardWhenTappedAround() {
  4. let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self,action: #selector(UIViewController.dismissKeyboard))
  5. view.addGestureRecognizer(tap)
  6. }
  7.  
  8. func dismissKeyboard() {
  9. view.endEditing(true)
  10. }
  11. }

现在在每个UIViewController,所有你要做的是调用函数

  1. override func viewDidLoad() {
  2. super.viewDidLoad()
  3. self.hideKeyboardWhenTappedAround()
  4. }

这个函数作为一个标准函数包含在我的仓库,其中包含了很多有用的Swift扩展,像这样,检查:https://github.com/goktugyil/EZSwiftExtensions

猜你在找的Swift相关文章