xcodeswift4selectoruitapgesturerecognizerunrecognized-selector

Unrecognized selector with UITapGestureRecognizer


I'm trying to add in my app the possibility to dismiss the keyboard when the user taps somewhere else out of the text fields. I'm implementing this functionality using UITapGestureRecognizer. I create a new UITapGestureRecognizer object using the Unrecognized selector with UITapGestureRecognizer(target: Any?, action: Selector?) and set the action parameter to a function that resigns the first responder of both the text fields I'm using in this view. I set everything properly adding the keyword @objc before the method I pass as action and using the #selector(dismissKeyboard) form, but when I run the app and tap on the view triggering the function the app crash and the console prints the error

" Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIView dismissKeyboard:]: unrecognized selector sent to instance 0x7ff93790f6b0' *** First throw call stack:"

    override func viewDidLoad() {
    super.viewDidLoad()

    // Set rounded corners
    textFieldView.layer.cornerRadius = 6
    logInButton.layer.cornerRadius = 6

    //HERE'S THE ISSUE

    let viewTapRecognizer = UITapGestureRecognizer(target: self.view, action: #selector(dismissKeyboard))
    self.view.addGestureRecognizer(viewTapRecognizer)

    auth = Auth.auth()

}

@objc func dismissKeyboard() {
    emailTextField.resignFirstResponder()
    passwordTextField.resignFirstResponder()
}

I Attach here the screenshots

First Screenshot

Second Screenshot

Third Screenshot


Solution

  • The target of Gesture is (self) not self.view because you are calling all the viewcontroller not just the view inside him,

    let viewTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard))
    view.addGestureRecognizer(viewTapRecognizer)
    

    and if you want to reduce hideKeyboard function just use

    view.endEditing(true)