首页 > 解决方案 > 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

标签: xcodeswift4selectoruitapgesturerecognizerunrecognized-selector

解决方案


Gesture 的目标是 (self) 而不是 self.view,因为您正在调用所有视图控制器,而不仅仅是他内部的视图,

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

如果你想减少 hideKeyboard 功能,只需使用

view.endEditing(true)

推荐阅读