Search code examples
objective-cuiscrollviewgesture-recognition

How to pass TouchUpInside event to a UIButton, without passing it to parent views?


I have a UIScrollview with paging enabled. There are 3 views (pages) inside this scroll view. There's a tap gesture on the parent view of the scrollview that shows and hides a navigation bar at the top.

The Problem: In one of the pages I want to add buttons. But the problem is that whenever i tap these buttons, the show/hide navigation bar method is also fired. What is the best way to pass the touch only to these buttons and not the the parent view of the scrollview?


Solution

  • NJones is on the right track, but I think there are some problems with his answer.

    I assume that you want to pass through touches on any button in your scroll view. In your gesture recognizer's delegate, implement gestureRecognizer:shouldReceiveTouch: like this:

    - (BOOL)gestureRecognizer:(UIGestureRecognizer *)recognizer shouldReceiveTouch:(UITouch *)touch {
    
        UIView *gestureView = recognizer.view;
        // gestureView is the view that the recognizer is attached to - should be the scroll view
    
        CGPoint point = [touch locationInView:gestureView];
        UIView *touchedView = [gestureView hitTest:point withEvent:nil];
        // touchedView is the deepest descendant of gestureView that contains point
    
        // Block the recognizer if touchedView is a UIButton, or a descendant of a UIButton
        while (touchedView && touchedView != gestureView) {
            if ([touchedView isKindOfClass:[UIButton class]])
                return NO;
            touchedView = touchedView.superview;
        }
        return YES;
    }