Search code examples
swiftuicollectionviewtvosuitapgesturerecognizer

How to add a tap gesture to multiple UIViewControllers


I'd like to print a message when an user taps twice on the remote of the Apple TV. I got this to work inside a single UIViewController, but I would like to reuse my code so that this can work in multiple views.

The code 'works' because the app runs without any problems. But the message is never displayed in the console. I'm using Swift 3 with the latest Xcode 8.3.3. What could be the problem?

The code of a UIViewController:

override func viewDidLoad() {
    super.viewDidLoad()

    _ = TapHandler(controller: self)

}

The code of the TapHandler class

class TapHandler {

    private var view : UIView?

    required init(controller : UIViewController) {

        self.view = controller.view

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.message))
        tapGesture.numberOfTapsRequired = 2
        self.view!.addGestureRecognizer(tapGesture)
        self.view!.isUserInteractionEnabled = true

    }

    @objc func message() {
        print("Hey there!")
    }

}

Solution

  • Your TapHandler just getting released. Try This:

    var tapHandler:TapHandler? = nil
    override func viewDidLoad() {
        super.viewDidLoad()
    
        tapHandler = TapHandler(controller: self)
    
    }
    

    I have tested the code and is working.