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