UILongPressGestureRecognizer未调用其目标方法

时间:2018-10-16 17:43:46

标签: ios delegates uigesturerecognizer ios12 uilongpressgesturerecogni

此功能适用于iOS 11上的设备,但我的设备已更新至iOS 12,它不再起作用:

//the viewcontroller is initiated with UIGestureRecognizerDelegate

let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPress))

//in cellForRowAt:
longPressGesture.minimumPressDuration = 1.0
longPressGesture.delegate = self
longPressGesture.cancelsTouchesInView = false
cell.addGestureRecognizer(longPressGesture)

@objc func longPress(longPressGestureRecognizer: UILongPressGestureRecognizer) {
     //never called
}

我还尝试将手势识别器添加到viewDidLoad中的按钮,以确保它与tableview无关,并且longPress函数仍未调用。

1 个答案:

答案 0 :(得分:1)

//the viewcontroller is initiated with UIGestureRecognizerDelegate
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPress))

似乎您正在尝试将longPressGesture设置为UIViewController的实例属性,同时为其提供目标和操作作为其初始化程序的一部分。那是行不通的,因为在初始化时,目标self不是实例。还没有实例;实例就是我们正在创建的过程!

相反,将该行移到cellForRowAt:中,如下所示:

//in cellForRowAt:
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPress))
longPressGesture.minimumPressDuration = 1.0
longPressGesture.delegate = self
longPressGesture.cancelsTouchesInView = false
cell.addGestureRecognizer(longPressGesture)