How to detect double-taps on cells in a UICollectionView

前端 未结 5 827
野的像风
野的像风 2021-01-30 11:01

I want to respond to double-taps on cells in a UICollectionView, and have a double-tap action cancel cell selection.

This is what I\'ve tried:

UITapGestu         


        
5条回答
  •  礼貌的吻别
    2021-01-30 11:37

    I don't see why you need the requireToFail. I use double-taps in a UICollectionView and it doesn't interfere with my single taps (used for selection).

    I use the following:

    UITapGestureRecognizer *doubleTapFolderGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(processDoubleTap:)];
    [doubleTapFolderGesture setNumberOfTapsRequired:2];
    [doubleTapFolderGesture setNumberOfTouchesRequired:1];
    [self.view addGestureRecognizer:doubleTapFolderGesture];
    

    Then, this:

    - (void) processDoubleTap:(UITapGestureRecognizer *)sender
    {
        if (sender.state == UIGestureRecognizerStateEnded)
        {
            CGPoint point = [sender locationInView:collectionView];
            NSIndexPath *indexPath = [collectionView indexPathForItemAtPoint:point];
            if (indexPath)
            {
                NSLog(@"Image was double tapped");
            }
            else 
            {
                DoSomeOtherStuffHereThatIsntRelated;
            }
        }
    }
    

    Seems to working fine -- the double tap is recognized and I can handle it as I wish (in this case I'm expanding the contents of a folder). But a single-tap will cause the tapped sell to be selected, which I haven't written any gesture recognition for.

    IMPORTANT EDIT:

    I am revisiting this question because I've seen that my original answer can be wrong in certain circumstances, and there is an apparent fix that seems to work.

    The following line needs to be added:

    doubleTapFolderGesture.delaysTouchesBegan = YES;
    

    which eliminates interference with the single tap for cell selection. This provides a much more robust setup.

提交回复
热议问题