【问题标题】:How to pass a Int to a method that is called bij with a #Selector in Swift如何将 Int 传递给在 Swift 中使用 #Selector 调用 bij 的方法
【发布时间】:2019-11-17 17:40:06
【问题描述】:

我想将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 无关的代码。

有人知道我会怎么做吗?

谢谢! 本吉

【问题讨论】:

标签: swift xcode uicollectionview uicollectionviewcell


【解决方案1】:

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

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

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

【讨论】:

  • 如果您首先编写处理程序,编译器将自动为您完成#selector 名称。在这种情况下,它的let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPress(recognizer:)))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-13
  • 2014-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多