9

If I have a scrollView with a subview and the subview has a pan gesture recognizer, the scrollView's pan gesture override's the subview's pan. What I want is the opposite, I think, so that is I drag a subview it will pan within the scroll view, yet if I touch another area the scroll view will pan as normal. Is there an easy way to set that up?

OWolf
  • 5,012
  • 15
  • 58
  • 93

3 Answers3

15

Here's what works for me:

UIPanGestureRecognizer *subviewPanRecognizer = [[UIPanGestureRecognizer alloc]
    initWithTarget:self action:@selector(panSubview:)];
[subview addGestureRecognizer:subviewPanRecognizer];

// play nice with subview's pan gesture
[scrollView.panGestureRecognizer 
    requireGestureRecognizerToFail:subviewPanRecognizer];
Benjamin Cheah
  • 1,401
  • 17
  • 23
  • That seems to be the default behaviour (that's what I'm observing in practice in a UIScrollView with a UIImageView subview). Could someone confirm/infirm? – Norswap Nov 01 '13 at 10:34
  • Works beautifully, especially when applying a delegate on the subview and implementing `gestureRecognizerShouldBegin:`. – Anthony Mills Jul 31 '15 at 22:20
1

Set canCancelContentTouches property of UIScrollView to false if you don't want to scroll on touching subviews.

Original answer

ViruMax
  • 1,216
  • 3
  • 16
  • 41
0

Overwrite these two delegate below,

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
return YES;

}

This will allow you to recognize both gestures, the default return is NO, so we need to overwrite it and return YES.

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
if ([gestureRecognizer isKindOfClass:[UITapGestureRecognizer class]]) {
    if ([otherGestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]]) {
        return NO;
    }else{
        return YES;
    }
}
return YES;

}

In this delegate you can do anything as you wish, as it's name the gestureRecoginzer will be required to fail by the otherGestureRecognizer, all you need to do is to judge what kind of these two gestures and return YES or NO.

KaKa
  • 559
  • 7
  • 18