Touch Events propagation in iOS

Vibhu picture Vibhu · Oct 22, 2012 · Viewed 7.2k times · Source

I am searching solution for very basic issues in native ios development.

I have such setup UIViewController (Full Screen) ----> UIView-Parent (Full Screen) ----> UIView-Child (Full Screen)

UIView-Child has subscribed to an event UITapGestureRecognizer and UIView-Parent has subscribed to event touchesBegan:withEvent

When a tap is made anywhere on the screen, an event goes to UIView-Child as well as UIView-Parent as both listen to different events.

But what I need is all the events get stopped in UIView-Child itself and does not propagate to UIView-Parent.

One way is to implement all the event listeners on UIView-Child using empty functions, but I am sure there should be a better way of doing it. Can somebody help me in this.

There is a second part to my question If UIView-Parent also start recognizing UITapGestureRecognizer event then as UIView-Child has implemented it, it does not propagate to UIView-Parent. Is there a way if needed I can make this propagation happen from UIView-Child to UIView-Parent.

Answer

George picture George · Oct 22, 2012

In order to avoid getting touches to the parent , when you show the child you can do this:

[parentView setUserInteractionEnabled:FALSE];

and reverse this when done. I think this is the easiest way.

Also , when using gesture recognizers , a good way to prevent / allow touch transmission is setting the right values for that gesture. Like this:

[gestureRecognizer setDelaysTouchesBegan:TRUE];
[gestureRecognizer setDelaysTouchesEnded:TRUE];
[gestureRecognizer setCancelsTouchesInView:TRUE];

The values , of course , can vary depending on what you want to achieve.

Hope this helps.

Cheers!