How can I supersede the built-in swipe gesture recognizer in UICollectionView?

佐手、 提交于 2019-12-04 20:27:32

There's an example on page 36 of the UICollectionView programming guide:

UITapGestureRecognizer* tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)];

NSArray* recognizers = [self.collectionView gestureRecognizers];

// Make the default gesture recognizer wait until the custom one fails.
for (UIGestureRecognizer* aRecognizer in recognizers) {
    if ([aRecognizer isKindOfClass:[UITapGestureRecognizer class]]) {
        [aRecognizer requireGestureRecognizerToFail:tapGesture];
    }
}

// Now add the gesture recognizer to the collection view.
tapGesture.numberOfTapsRequired = 2;
[self.collectionView addGestureRecognizer:tapGesture];

Original answer

Have a look at UITapGestureRecognizerDelegate, which can be used to allow two gesture recognizers to process touches at once:

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

For more info, see a tutorial such as this:

http://www.raywenderlich.com/6567/uigesturerecognizer-tutorial-in-ios-5-pinches-pans-and-more

Before your new UILongPressGestureRecognizer transnitions from the possible state, he will ask its delegate gestureRecognizerShouldBegin:. You can use that delegate method to cancel (force to failed state) any other gesture recogniser attached to the same view.

You do this by implementing the following as a delegate for your new UILongPressGestureRecognizer:

@implementation DragPictogramGestureRecognizerDelegate

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    for (UIGestureRecognizer *gr in gestureRecognizer.view.gestureRecognizers) {
        if ([gr isKindOfClass:[UILongPressGestureRecognizer class]] == NO) {
            gr.enabled = NO;
            gr.enabled = YES;
        }
    }
    return YES;
}

@end

Further more, in order to allow the user to use your new UILongPressGestureRecognizer with one finger, and use another finger to scroll the UICollectionView at the same time, you can implement the following delegate in the same class.

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!