'Adding UILongPressGesture to Cell not CollectionView

I am trying to add UILongGestureRecognizer to my Custom CollectionView Cell but handler function never called. This is my gesture and handlerFunc from custom cell:

let longPress = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(_:)))

@objc func handleLongPress(_ recognizer: UILongPressGestureRecognizer) {
    switch recognizer.state {
    case .possible:
        break
    case .began:
        print("began")
        break
    case .changed:
        break
    case .ended:
        print("ended")
        break
    case .cancelled:
        break
    case .failed:
        break
    @unknown default:
        break
    }
}

Also, this is my cell configure function:

func configure(with viewModel: RecordsCollectionViewCellViewModel, itemCount: Int) {
    longPress.numberOfTapsRequired = 1
    longPress.minimumPressDuration = 0.3
    longPress.delaysTouchesBegan = true
    longPress.delegate = self
    
    self.bringSubviewToFront(gestureView)
    gestureView.isUserInteractionEnabled = true
    gestureView.addGestureRecognizer(longPress)

}

The gestureView is the transparent view at the top of the cell.



Solution 1:[1]

I've tried this in the past and had issues, I believe to do with contextMenu interaction on the actual collectionView.

You can fix it by putting the gesture handler on the collectionView itself and getting the gesture location, then cell at location as per this link;

how-to-make-tableviewcell-handle-both-tap-and-longpress

Solution 2:[2]

only call setLongPress() in viewDidLoad()

func setLongPress(){
     let lpgr = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(_:)))
     lpgr.minimumPressDuration = 0.5
     lpgr.delaysTouchesBegan = true
     lpgr.delegate = self
     self.CollectionView.addGestureRecognizer(lpgr)
}

@objc func handleLongPress(_ gestureRecognizer: UILongPressGestureRecognizer?) {
    if gestureRecognizer?.state != .ended {
        return
    }
    let p = gestureRecognizer?.location(in: projectCollectionView)

    let indexPath = CollectionView.indexPathForItem(at: p ?? CGPoint.zero)
    if indexPath == nil {
        print("couldn't find index path")
    } else {
        // get the cell at indexPath (the one you long pressed)
        var cell: UICollectionViewCell? = nil
        if let indexPath = indexPath {
            // your action here
        }
        // do stuff with the cell
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kric
Solution 2 sayed abdo