Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use UILongPressGestureRecognizer with a UICollectionViewCell in Swift?

Tags:

I would like to figure out how to println the indexPath of a UICollectionViewCell when I long press on a cell.

How can I do that in Swift?

I have looked all over for an example of how to do this; can't find one in Swift.

like image 844
webmagnets Avatar asked Mar 24 '15 19:03

webmagnets


People also ask

How do you use UILongPressGestureRecognizer?

UILongPressGestureRecognizer is a concrete subclass of UIGestureRecognizer . The user must press one or more fingers on a view and hold them there for a minimum period of time before the action triggers. While down, the userʼs fingers canʼt move more than a specified distance or the gesture fails.

What is Uicollectionviewcell in Swift?

An object that manages an ordered collection of data items and presents them using customizable layouts.


1 Answers

First you your view controller need to be UIGestureRecognizerDelegate. Then add a UILongPressGestureRecognizer to your collectionView in your viewcontroller's viewDidLoad() method

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

The method to handle long press:

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

This code is based on the Objective-C version of this answer.

like image 200
ztan Avatar answered Mar 06 '23 07:03

ztan