如果你設置的 UIPanGestureRecognizer 不起作用,可能是因爲 UIPanGestureRecognizer 初始化方式不對。
如下面代碼所示,如果你在成員變量裏面初始化,並且指定 target 爲 self,這會導致 onPan 方法無法被調用。
class YourView: UIView {
var uiPan = UIPanGestureRecognizer(target: self, action: #selector(onPan))
init() {
addGestureRecognizer(uiPan)
}
@objc func onPan() {
//...
}
}
可以選擇先初始化,隨後在綁定 target。
下面的代碼將會正常工作。
class YourView: UIView {
var uiPan = UIPanGestureRecognizer()
init() {
uiPan.addTarget(self, action: #selector(onPan))
addGestureRecognizer(uiPan)
}
@objc func onPan() {
//...
}
}