MRoot
MRoot

Reputation: 45

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

Upvotes: 1

Views: 1269

Answers (2)

Manish Punia
Manish Punia

Reputation: 877

You can subclass UIWindow class and handle all the events in - (void)sendEvent:(UIEvent *)event there like sending notifications to all the views or communicate with some other way. Check the following repository for more info: https://github.com/mwinoto/TapDetectingWindow

Upvotes: 1

Abbas Sabeti
Abbas Sabeti

Reputation: 151

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.

Upvotes: 0

Related Questions