Tuesday, June 4, 2013

UIScrollView panGestureRecognizer example in Objective C (iOS).

UIScrollView panGestureRecognizer

The underlying gesture recognizer for pan gestures. (read-only)

@property(nonatomic, readonly) UIPanGestureRecognizer *panGestureRecognizer

Discussion of [UIScrollView panGestureRecognizer]
Your application accesses this property when it wants to more precisely control which pan gestures are recognized by the scroll view.

UIScrollView panGestureRecognizer example.
panGestureRecognizer is only available in iOS 5.0+.

I solved it by adding a category to UIScrollView.

@interface UIScrollView(panGestureRecognizer)
@implementation UIScrollView(panGestureRecognizer)
// iOS5 has a panGestureRecognizer property
// Add a getter for iOS 4.3+
- (UIPanGestureRecognizer *)panGestureRecognizer
    for (UIGestureRecognizer *gestureRecognizer in self.gestureRecognizers)
        if ([gestureRecognizer isKindOfClass: [UIPanGestureRecognizer class]]) {
            return (UIPanGestureRecognizer *)gestureRecognizer;
    return nil;

Example of [UIScrollView panGestureRecognizer].
You can make the code even shorter.

//disables the built-in pan gesture
scrollView.panGestureRecognizer.enabled = NO;

//add your own
UIPanGestureRecognizer *myPan = [[UIPanGestureRecognizer alloc] init...];
[scrollView addGestureRecognizer:myPan];
[myPan release];

UIScrollView panGestureRecognizer example.
As of iOS 5, UIScrollView exposes its UIPanGestureRecognizer. Set your custom swipe’s delegate to self and make the gestureRecognizer a property or ivar, and make your class conform to the <UIGestureRecognizerDelegate> protocol. Then, implement UIGestureRecognizerDelegate’s – gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer: like so:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
    if ([gestureRecognizer isEqual:self.swipe] && [otherGestureRecognizer isEqual:self.scrollView.panGestureRecognizer])
         return NO;
    return YES; // the default for this method

End of UIScrollView panGestureRecognizer example article.