xcode - 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
解决方案
Gesture 的目标是 (self) 而不是 self.view,因为您正在调用所有视图控制器,而不仅仅是他内部的视图,
let viewTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard))
view.addGestureRecognizer(viewTapRecognizer)
如果你想减少 hideKeyboard 功能,只需使用
view.endEditing(true)
推荐阅读
- android - android用户scroe栏自定义
- sql - 将所有表列转换为二进制字符串
- amazon-web-services - 用于 aws-chime-sdk 的 amazon api gateway API 给出内部服务器错误作为响应
- javascript - 在 Javascript 中显示来自对象的数据
- r - 如何基于以字符串编写的相似但不准确的时间变量合并两个数据集。使用 R?
- bash - (bash 脚本)有没有办法获得写入文件失败尝试的实际 errno?
- loops - 每个循环目标动态选择器上的 SCSS 不会产生结果
- html - Blazor 键盘导航到 ADA 网站
- emacs - 如何从终端退出 Emacs?
- java - 为什么不使用字符串的长度作为开始索引调用子字符串抛出 OutOfBoundsException?