Search code examples
swiftxcodeuitapgesturerecognizergesture-recognition

How to detect touch event across multiple views on my view controller?


In my viewController I have programmatically created several squares as sub-views. Imagine it as a chessboard.

I would like to implement a method that executes some actions upon the sub-view (e.g., change the background color of a single square) when it gets touched by the user.

I have unsuccessfully tried with the UITapGestureRecognizer - I have read from Apple documentation that it applies only to one view at a time.

Do you have any suggestions?

Many thanks


Solution

  • Do it like this

    class YourCustomView : UIView {
    
        func  addTapGesture(action : @escaping ()->Void ){
            self.gestureRecognizers?.forEach({ (gr) in
                self.removeGestureRecognizer(gr)
            })
            let tap = MyTapGestureRecognizer(target: self , action: #selector(self.handleTap(_:)))
            tap.action = action
            tap.numberOfTapsRequired = 1
    
            self.addGestureRecognizer(tap)
            self.isUserInteractionEnabled = true
    
        }
    }
    

    or you can use this even in a extension of UIView if you're going to use it in multiple types of UIViews.

    And then use it like:

    let yourView = YourCustomView()
    yourView.addTapGesture{[weak self] in
        //implement tap event here
    }
    

    Notice that [weak self] is going to avoid getting a strong reference for closure to avoid a retain cycle there.