0

I want to add a longPressGestureRecocnizer to a collection view cell and pass in the indexPath of the cell to work with it. I tried to do this by adding this to the cellForItemAt method:

let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressGetstureFunction(indexPath:)))
cell.addGestureRecognizer(longPressGesture)

This is the method I call with the #Selector:

@objc func longPressGetstureFunction(indexPath: Int) {

        print("long press gesture detected")
        Alert.showColectionViewDataAlert(on: self, indexRow: indexPath)

    }

But when I pass in a integer for the indexPath like this:

let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressGetstureFunction(indexPath: 5)))

I get the following error message from Xcode:

Argument of '#selector' does not refer to an '@objc' method, property, or initializer

I google a lot on this topic, and I saw also a few answers to the same kind of question on StackOverflow, but all the answer either have objective-C code, or code that is not relevant to colectionView's.

Does anyone have an idea of how I would do this?

Thanks! Benji

BSM
  • 87
  • 2
  • 12
  • Does this answer your question? [Passing arguments to selector in Swift](https://stackoverflow.com/questions/43251708/passing-arguments-to-selector-in-swift) – trndjc Nov 17 '19 at 17:50
  • @bsod I saw that answer when I googled, but it doest answer my question – BSM Nov 17 '19 at 19:43

1 Answers1

1

You cannot do this, the gesture recognizer target can take only a single parameter and that is the recognizer itself.

Use the point of the recognizer to find the indexPath instead:

  @objc private func longPress(recognizer: UILongPressGestureRecognizer) {
    guard let indexPath = collectionView.indexPathForItem(at: recognizer.location(in: collectionView)) else {
        return
    }
    // Do Stuff with indexPath here
  }
Josh Homann
  • 15,933
  • 3
  • 30
  • 33
  • 1
    if you write the handler first the compiler will auto complete the #selector name for you. in this case its `let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPress(recognizer:)))` – Josh Homann Nov 17 '19 at 19:44