How to detect double-taps on cells in a UICollectionView

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

    For readers looking for a swift answer, this is a mix of @RegularExpression and @Edwin Iskandar answer.

    In your controller holding the collectionView add the following lines:

    
      private var doubleTapGesture: UITapGestureRecognizer!
      func setUpDoubleTap() {
        doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(didDoubleTapCollectionView))
        doubleTapGesture.numberOfTapsRequired = 2
        collectionView.addGestureRecognizer(doubleTapGesture)
    
        // This line delay the single touch message to the collection view.
        // Simple touch will be sent only when the double tap recogniser is sure
        // this is a simple tap.
        // You can remove it if you don't mind having both a simple tap and double
        // tap event.
        doubleTapGesture.delaysTouchesBegan = true  
      }
    
      @objc func didDoubleTapCollectionView() {
        let pointInCollectionView = doubleTapGesture.location(in: collectionView)
        if let selectedIndexPath = collectionView.indexPathForItem(at: pointInCollectionView) {
          let selectedCell = collectionView.cellForItem(at: selectedIndexPath)
    
          // Print double tapped cell's path
          print(selectedCell)
        }
      }
    

提交回复
热议问题