为什么 UIPanGestureRecognizer 不起作用?

如果你设置的 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() {
        //...
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章