首页 > 解决方案 > 添加调用另一个类中的函数的点击手势

问题描述

我添加了UITapGestureRecognizer一个元素。我希望在识别点击手势后调用的函数在另一个类中。

这是我的代码:

let selectMoment = SelectMomentClass(countUserMoment: 1, cardView: self.cardView)
selectMoment.draw()
let gesture = UITapGestureRecognizer(target: self, action: #selector(selectMoment.selectMomentAction))
cardView.addGestureRecognizer(gesture)

SelectMomentClass包含我的功能:

@objc func selectMomentAction(sender : UITapGestureRecognizer) {
    print("card selectMoment is Tapped")
}

但是当我运行代码时,我遇到了这个错误:

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

我的代码哪里出错了?这是我需要更改的目标参数。我可以在另一个类中调用函数吗?


我在 Objective-C 中发现了一个类似的问题,但它对我没有帮助。

标签: iosswiftuitapgesturerecognizer

解决方案


使用这个。您的方法在selectMomentClass类中定义,然后您必须将目标添加为selectMomentClass对象,将选择器添加为#selector(selectMoment.SelectPictureAction)

let selectMoment = SelectMomentClass(countUserMoment: 1, cardView: self.cardView)
let gesture = UITapGestureRecognizer(target: selectMoment, action: #selector(selectMoment.SelectPictureAction(_:)))

selectMomentClass 中的方法签名如下

@objc func selectPictureAction(_ sender : UITapGestureRecognizer) {
        print("card selectMoment is Tapped")
}

推荐阅读