How to detect double-taps on cells in a UICollectionView

前端 未结 5 828
野的像风
野的像风 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:56

    There are a bunch of good solutions here but unfortunately they didn't work reliably for me (e.g. I could not get the double tap to trigger consistently possibly because I was also implemented didSelectItemAtIndexPath).

    What worked for me was adding the (double)tap gesture recognizer to the collection view instead of the cell. In its action selector I would determine which cell was double tapped and do whatever I needed to do. Hopefully this helps someone:

    - (void)viewDidLoad
    {
        UITapGestureRecognizer *doubleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didDoubleTapCollectionView:)];
        doubleTapGesture.numberOfTapsRequired = 2;
        [self.collectionView addGestureRecognizer:doubleTapGesture];
    }
    
    - (void)didDoubleTapCollectionView:(UITapGestureRecognizer *)gesture {
    
        CGPoint pointInCollectionView = [gesture locationInView:self.collectionView];
        NSIndexPath *selectedIndexPath = [self.collectionView indexPathForItemAtPoint:pointInCollectionView];
        UICollectionViewCell *selectedCell = [self.collectionView cellForItemAtIndexPath:selectedIndexPath];
    
        // do something
    }
    

提交回复
热议问题