将gestureRecognizer添加到tableView单元格

时间:2016-10-10 17:31:40

标签: ios swift xcode uitableview uigesturerecognizer

我目前有一个带有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")
}

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

  

由于未捕获的异常而终止应用   ' NSInvalidArgumentException',原因:' - [TestingGround.TableTesting   longPressAction:]:发送到实例的无法识别的选择器   0x7f9afbc055d0'

我猜不出正确的信息没有被传递到函数中,但我不确定?

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

而不是:

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

使用:

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

答案 1 :(得分:0)

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

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
}

干杯!