electronickid
electronickid

Reputation: 11

Swift - Unrecognized Selector to instance - UITapGestureRecognizer

I'm trying to set up a UITapGestureRecognizer but I keep having the following error :

[projet.View tapA]:] unrecognized selector sent to instance adress

Here's my code :

Class View :

class View: UIView {

     init(frame: CGRect, s: TimeInterval, position : CGPoint , size : CGSize) {

        let tap = UITapGestureRecognizer(target: self, action:   
        #selector(ViewController.tapA(sender:)))
        tap.numberOfTapsRequired = 1
        self.addGestureRecognizer(tap)
     }
}    

Class ViewController (UIViewController) :

@objc func tapA (sender : UITapGestureRecognizer){
        //For now : 
        print("Jump")
   }

I haven't been able to find any problems like this one. Any help would be much appreciated! Thank you in advance.

Upvotes: 0

Views: 681

Answers (2)

flamyoad
flamyoad

Reputation: 565

In my case, I accidentally used self.view instead of self

// Wrong
let tap = UITapGestureRecognizer(target: self.view, action: #selector(dismissVC))

// Correct
let tap = UITapGestureRecognizer(target: self, action: #selector(dismissVC))

Upvotes: 0

lpizzinidev
lpizzinidev

Reputation: 13289

Instead of creating the selector in the ViewController class, create it in the View class and pass an instance of the view controller to it, then in the selector just execute the code of the ViewController:

View

class View: UIView {

     var viewController: ViewController!

     init(frame: CGRect, s: TimeInterval, position : CGPoint , size : CGSize) {
        let tap = UITapGestureRecognizer(target: self, action: #selector(tapA(_:)))
        tap.numberOfTapsRequired = 1
        self.addGestureRecognizer(tap)
     }

     @objc 
     private func tapA(_ sender: UITapGestureRecognizer) {
        guard let vc = viewController as? ViewController else { return }
        vc.execTapA()
     }
}    

ViewController

func execTapA() {
    // Execute the code you need
}

To pass the reference of ViewController to the view just call, in your ViewController's viewDidLoad method:

view.viewController = self

Upvotes: 1

Related Questions