swift :"Unrecognized selector sent to instance",Xcode 9.4.1

标签 swift uitapgesturerecognizer unrecognized-selector xcode9.4

谁能帮我解决这个问题吗?

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.delegate=self
    tableView.dataSource=self
    searchBar.autocorrectionType = .yes
    searchBar.delegate=self
    searchBarView.translatesAutoresizingMaskIntoConstraints=false

    let tap:UIGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector(("tapCancel:")))

    searchBarView.addGestureRecognizer(tap)
    tableView.addGestureRecognizer(tap)
    tableView.isUserInteractionEnabled=true
}
...
func tapCancel(sender:UITapGestureRecognizer){
    hideSearchBarView()
    isSearchon=false
    print("Tap cancel!")
}

每次我点击 View 时,它都会崩溃。 “无法识别的选择器发送到实例 0x7feb85d109e0”

我将不胜感激任何帮助! 谢谢!

最佳答案

我相信原因是由于方法名称如何在 Swift 和 Objective-C 之间映射,这是 Cocoa 实现和整个目标/操作机制的基础。

就您而言,Swift 方法:

@objc func tapCancel(sender:UITapGestureRecognizer)

...对应于Objective-C选择器:

-tapCancelWithSender:

注意:为了使用目标/操作范例(即通过选择器调用),该方法需要声明为@objc。替代属性@IBOutlet(与Interface Builder 结合使用)也支持这一点。 (向@rmaddy致敬)

为了删除“withSender”部分并获得与 tapCancel: 匹配的选择器,您需要告诉 Swift 删除参数标签 sender,像这样:

func tapCancel(_ sender:UITapGestureRecognizer) // Notice the underscore (_)

另外,根据@dan的评论,也许你可以使用:

#selector(self.tapCancel(_:))

或更简洁地说,正如(再次感谢)@rmaddy 所指出的,只是:

#selector(tapCancel)

(Xcode 会尝试将其自动补全为 #selector(tapCancel(_:)),但较短的语法也可以使用,并且方法名称会突出显示)

我不熟悉您使用的 Selector() 语法,所以我尝试了一下,然后发现:

enter image description here (选择器与编译器可以“看到”的任何方法都不匹配)。

enter image description here (添加“withSender”后,编译器可以匹配该方法,但建议使用更好的 #selector(... 语法)。

正如 @rmaddy 在评论中指出的那样,使用较短的 #selector(doSomething) 语法(没有冒号,没有下划线,没有 self)也消除了是否需要“withSender”的问题。

关于 swift :"Unrecognized selector sent to instance",Xcode 9.4.1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50920223/

相关文章:

当我按下主页按钮然后恢复它时,ios7 应用程序崩溃

ios - 无法识别的选择器发送到实例 ***

ios - 处理后 AVFoundation 相机图像质量下降

swift - Firestore 返回一个 Dictionary<String, Any> 但我需要将值作为 String

ios - 如何删除 Collection View 单元格之间的空间?

ios - 通过 View 层次结构传播触摸事件(UIView 内的 UIButton)

arrays - Swift 存储自定义对象数组

ios - 在多个 UIImageView 上点击手势

ios - SWIFT4 : How to have two tap gestureRecognizers work together

ios - 无法识别的选择器发送到实例 0x7f995be07650