首页 > 解决方案 > 如何快速双击(而不是单击)集合视图单元格?

问题描述

现在,我在 collectionview 单元格中有一堆消息。我现在单击单元格的代码是

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    print("Which cell: ", indexPath)
}

我如何使它只有在双击而不是单击时才会打印?

标签: iosswift

解决方案


You can add UITapGestureRecognizer in collection view.

  private var doubleTapGesture: UITapGestureRecognizer!
    func setUpDoubleTap() {
        doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(didDoubleTapCollectionView))
        doubleTapGesture.numberOfTapsRequired = 2
        collectionView.addGestureRecognizer(doubleTapGesture)
        doubleTapGesture.delaysTouchesBegan = true
    }

Call above method from your viewDidLoad as

override func viewDidLoad() {
        super.viewDidLoad()
        setUpDoubleTap()
    }

Then add Gesture selector method in your class

 @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("Which cell: ", selectedIndexPath.row)
            print(" double tapped")
        }
    }

didDoubleTapCollectionView method will call only when you will double tap on collection view cell item.

I hope above example will solve your problem.


推荐阅读