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

问题描述 投票:0回答:1

我想将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

我在这个主题上用谷歌搜索很多,在StackOverflow上我也看到了相同问题的一些答案,但是所有答案都包含Objective-C代码或与colectionView无关的代码。

有人知道我该怎么做吗?

谢谢!Benji

swift xcode uicollectionview uicollectionviewcell
1个回答
0
投票

您不能执行此操作,手势识别器目标只能使用一个参数,而该参数就是识别器本身。

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

  @objc private func longPress(recognizer: UILongPressGestureRecognizer) {
    guard let indexPath = collectionView.indexPathForItem(at: recognizer.location(in: collectionView)) else {
        return
    }
    // Do Stuff with indexPath here
  }
© www.soinside.com 2019 - 2024. All rights reserved.