-1

I implemented this function to detect touches outside keyboard and hide the keyboard

extension UIViewController {
    func hideKeyboardWhenTappedAround() {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }

but how can I do callback when a user touches outside the keyboard? I want another action to happen. I don't want only the keyboard to be hidden.I want to do other function including hiding keyboard everytime the keyboard is hidden I wa=ish to have more actions.

AlmoDev
  • 969
  • 2
  • 18
  • 46
  • Possible duplicate of [iphone, dismiss keyboard when touching outside of UITextField](https://stackoverflow.com/questions/5306240/iphone-dismiss-keyboard-when-touching-outside-of-uitextfield) – Mike Mertsock Dec 12 '17 at 21:15
  • I want to do other function including hiding keyboard everytime the keyboard is hidden I wish to have more actions. – AlmoDev Dec 13 '17 at 07:05

2 Answers2

1

It's super easy. just need to create a function inside the viewcontroller that you want to call and add UIViewController.dismissKeyboard() in it

@objc func dismissKeyboardAndOtherStuff(){
 UIViewController.dismissKeyboard()
 // do other stuff

}

in you extension change the selector to reflect your new function

        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboardAndOtherStuff))
Andras M.
  • 838
  • 7
  • 12
0

I usually create an extension for this case:

extension UIViewController {
    func hideKeyboard() {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }

    func dismissKeyboard() {
        view.endEditing(true)
    }
}

Basically you add a gesture to the view

and you can call it from any ViewController like this:

hideKeyboard()
Sergio Trejo
  • 632
  • 8
  • 23