skip to Main Content

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

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search