How do I use UILongPressGestureRecognizer with a UICollectionViewCell in Swift?

31,428

Solution 1

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.

Solution 2

ztan answer's converted to swift 3 syntax and minor spelling update:

func handleLongPress(_ gestureRecognizer: UILongPressGestureRecognizer) {
    if gestureRecognizer.state != UIGestureRecognizerState.ended {
      return
    }

    let p = gestureRecognizer.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")
    }
}

Solution 3

One thing I found was that:

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

doesn't place pin until you release the longpress, which is OK, but I found

if gestureRecognizer.state == UIGestureRecognizerState.Began { }  

around the whole function will prevent multiple pin placements while letting the pin appear as soon as the timer delay is satisfied.

Also, one typo above: Reconizer -> Recognizer

Solution 4

The method handleLongProgress converted to swift 3 syntax works fine. I just want to add that the initialization of lpgr should be changed to:

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

Solution 5

Swift 5 & Swift 4 Table View Cell

override func viewDidLoad() {
    //MARK:- Add Long Gesture
    let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressed))
    longPressGesture.minimumPressDuration = 1.0 // 1 second press
    longPressGesture.allowableMovement = 15 // 15 points
    longPressGesture.delegate = self
    self.tablev.addGestureRecognizer(longPressGesture)
}


//MARK:- Long Press Gesture
@objc func longPressed(sender: UILongPressGestureRecognizer)
{

    if sender.state == UIGestureRecognizer.State.ended {
        return
    }
    else if sender.state == UIGestureRecognizer.State.began
    {
        let p = sender.location(in: self.tablev)
        let indexPath = self.tablev.indexPathForRow(at: p)

        if let index = indexPath {
            var cell = self.tablev.cellForRow(at: index)
            // do stuff with your cell, for example print the indexPath
            print(index.row)
            print("longpressed Tag: \(index.row)")
        } else {
            print("Could not find index path")
        }
    }
}
Share:
31,428
webmagnets
Author by

webmagnets

I am bible teacher. My second language is Spanish, but I am now learning Chinese so I can teach the bible in that language too.

Updated on July 18, 2022

Comments

  • webmagnets
    webmagnets almost 2 years

    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.