ios – 如何在Swift的UICollectionViewCell中使用UILongPressGestureRecognizer?
當我長時間按下一個單元格時,我想知道如何列印一個UICollectionViewCell的indexPath.
如何在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版本的ofollow,noindex" target="_blank">this answer .
程式碼日誌版權宣告:
翻譯自:http://stackoverflow.com/questions/29241691/how-do-i-use-uilongpressgesturerecognizer-with-a-uicollectionviewcell-in-swift