如何在Swift中使用带有UICollectionViewCell的UILongPressGestureRecognizer?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (60)

我想了解如何在长按单元格时打印UICollectionViewCell的indexPath。

我如何在Swift中做到这一点?

我已经看过所有关于如何做到这一点的例子; 在Swift中找不到一个。

提问于
用户回答回答于

首先你需要你的视图控制器UIGestureRecognizerDelegate。然后在viewcontroller的viewDidLoad()方法中添加一个UILongPressGestureRecognizer到你的collectionView

class ViewController: UIViewController, UIGestureRecognizerDelegate {

     override func viewDidLoad() {
         super.viewDidLoad()

        let lpgr = UILongPressGestureRecognizer(target: self, action: "handleLongPress:")
         lpgr.minimumPressDuration = 0.5
         lpgr.delaysTouchesBegan = true
         lpgr.delegate = self
         self.collectionView.addGestureRecognizer(lpgr)
    }

处理长按的方法:

func handleLongPress(gestureReconizer: UILongPressGestureRecognizer) {
        if gestureReconizer.state != UIGestureRecognizerState.Ended {
            return
        }

        let p = gestureReconizer.locationInView(self.collectionView)
        let indexPath = self.collectionView.indexPathForItemAtPoint(p)

        if let index = indexPath {
            var cell = self.collectionView.cellForItemAtIndexPath(index)
            // do stuff with your cell, for example print the indexPath
             println(index.row)
        } else {
            println("Could not find index path")
        }
    }
用户回答回答于
func handleLongPress(_ gestureReconizer: UILongPressGestureRecognizer) {
    if gestureReconizer.state != UIGestureRecognizerState.ended {
      return
    }

    let p = gestureReconizer.location(in: collectionView)
    let indexPath = collectionView.indexPathForItem(at: p)

    if let index = indexPath {
      var cell = collectionView.cellForItem(at: index)
      // do stuff with your cell, for example print the indexPath
      print(index.row)
    } else {
      print("Could not find index path")
    }
}

扫码关注云+社区

领取腾讯云代金券