添加在另一个类中调用函数的水龙头手势

时间:2018-07-29 19:21:59

标签: ios swift uitapgesturerecognizer

我向元素添加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中发现了类似的question,但对我没有帮助。

2 个答案:

答案 0 :(得分:1)

使用this。您的方法是在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 selectMomentAction(_ sender : UITapGestureRecognizer) {
        print("card selectMoment is Tapped")
}

答案 1 :(得分:0)

由于该对象是局部变量,因此在函数结束后将其释放,因此使其成为其类内的实例变量

let selectMoment = SelectMomentClass(countUserMoment: 1, cardView: self.cardView)
相关问题