如何在UISollectionViewCell中使用UILongPressGestureRecognizer?

我想弄清楚当我长按一个单元格时,如何打印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") } } 

此代码基于此答案的Objective-C版本。

ztan答案转换为swift 3语法:

 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") } } 

我发现的一件事是:

 if gestureReconizer.state != UIGestureRecognizerState.Ended { return } 

不放置引脚,直到你释放longpress,这是可以的,但我发现

 if gestureRecognizer.state == UIGestureRecognizerState.Began { } 

在满足定时器延时的同时,围绕整个function将防止多个引脚的放置,同时让引脚出现。

此外,上面的一个错字:Reconizer – > Recognizer

handleLongProgress转换为swift 3语法的方法正常工作。 我只想补充一下,lpgr的初始化应该改为:

 let lpgr = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(gestureReconizer:)))