Search code examples
iosswiftuitapgesturerecognizer

Adding tap Gesture that calls a function in another class


I added a UITapGestureRecognizer to an element. I want that function called after the tap gesture was recognized is in another class.

This is my code :

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

and my SelectMomentClass contains my function:

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

But when I run the code I have this error:

unrecognized selector sent to instance

Where does my code go wrong? This is the target parameter that I need to change. Can I called a function in another class?


I found a similar question in Objective-C but it does not help me.


Solution

  • Since the object is a local variable it's deallocated after functions ends so make it an instance variable inside its class

    let selectMoment = SelectMomentClass(countUserMoment: 1, cardView: self.cardView)