OWolf
OWolf

Reputation: 5132

UIScrollView overrides my subview's pan gesture recognizers

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?

Upvotes: 9

Views: 12740

Answers (3)

ViruMax
ViruMax

Reputation: 1218

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

Original answer

Upvotes: 1

KaKa
KaKa

Reputation: 559

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.

Upvotes: 0

Benjamin Cheah
Benjamin Cheah

Reputation: 1401

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];

Upvotes: 15

Related Questions