将 gestureRecognizer 添加到 tableView 单元格

Add a gestureRecognizer to a tableView cell

我目前有一个包含 3 个单元格的 TableViewController,我正在尝试添加一个长按手势识别器,以便在检测到时只打印到日志中。

我添加了:

class TableTesting: UITableViewController, UIGestureRecognizerDelegate 

在我的 tableView 方法中,我创建了一个 UILongPressGestureRecognizer:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.textLabel?.text = "Gesture Recognizer Testing"
    var lpgr = UILongPressGestureRecognizer(target: self, action: "longPressAction:")
    lpgr.minimumPressDuration = 2.0
    lpgr.delegate = self
    cell.addGestureRecognizer(lpgr)
    return cell
}

我还创建了函数 longPressAction

func longPressAction(gestureRecognizer: UILongPressGestureRecognizer) {
    print("Gesture recognized")
}

我遇到的问题是在编译代码并尝试长按我的单元格时,应用程序崩溃并且出现此错误:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[TestingGround.TableTesting longPressAction:]: unrecognized selector sent to instance 0x7f9afbc055d0'

我以某种方式猜测没有将正确的信息传递到函数中,但我不确定?

如有任何帮助,我们将不胜感激。

而不是:

var lpgr = UILongPressGestureRecognizer(target: self, action: "longPressAction:")

使用:

let lpgr = UILongPressGestureRecognizer(target: self, action: #selector(longPressAction(gestureRecognizer:)))

问题是你大部分时间都在正确。 使用此代码:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.textLabel?.text = "Gesture Recognizer Testing"
    let lpgr = UILongPressGestureRecognizer(target: self, action: #selector(longPressAction(_:)))
    lpgr.minimumPressDuration = 2.0
    lpgr.delegate = self
    cell.contentView.addGestureRecognizer(lpgr)
    return cell
}

干杯!