如何使用 Swift 中的#Selector 将 Int 传递给名为 bij 的方法

How to pass a Int to a method that is called bij with a #Selector in Swift

我想将 longPressGestureRecocnizer 添加到集合视图单元格并传入单元格的 indexPath 以使用它。我试图通过将此添加到 cellForItemAt 方法来做到这一点:

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

这是我用#Selector 调用的方法:

@objc func longPressGetstureFunction(indexPath: Int) {

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

    }

但是当我像这样为 indexPath 传递一个整数时:

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

我从 Xcode 收到以下错误消息:

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

我google很多关于这个话题,我也在 Whosebug 上看到了一些对同类问题的回答,但是所有的答案要么有 objective-C 代码,要么就是代码与 collectionView 无关。

有人知道我会怎么做吗?

谢谢! 本机

你不能这样做,手势识别器目标只能接受一个参数,那就是识别器本身。

改用识别器的点来查找indexPath:

  @objc private func longPress(recognizer: UILongPressGestureRecognizer) {
    guard let indexPath = collectionView.indexPathForItem(at: recognizer.location(in: collectionView)) else {
        return
    }
    // Do Stuff with indexPath here
  }