Unrecognized selector with UITapGestureRecognizer

那年仲夏 提交于 2019-12-20 07:32:04

问题


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


回答1:


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)


来源:https://stackoverflow.com/questions/51767973/unrecognized-selector-with-uitapgesturerecognizer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!