Getting gestures to work with Subclassed UIButton

佐手、 提交于 2019-12-12 03:04:30

问题


I have a subclassed UIButton (DragButton) that I would like to be able to perform pan / pinch / rotate on. Instances of DragButton are created programmatically. There may be 1, there may be 20. All depends on the user.

I am experiencing issues in getting these subclassed buttons to properly work with gestures. The main issue is none of the gestures trigger! Within DragButton class, inside the awakeFromNib instance method, the gestures don't work at all. Inside layoutSubviews, the panning works properly the first drag, but each subsequent hold and drag increases the velocity of the movement a considerably amount. (Pinch and Rotate work properly in layoutSubviews though.) It's almost like layoutSubviews is 'doubling up' the gestures on each interaction. But awakeFromNib doesn't work at all. My guess here is the new buttons have not been unarchived yet.

Here is the code in DragButton

class DragButton: UIButton, UIGestureRecognizerDelegate {
    override func awakeFromNib() {
        let panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(self.draggedView(_:)))
        let pinchRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(self.pinchedView(_:)))
        let rotateRecognizer = UIRotationGestureRecognizer(target: self, action: #selector(self.rotatedView(_:)))  

        panRecognizer.delegate = self
        pinchRecognizer.delegate = self
        rotateRecognizer.delegate = self

        self.isUserInteractionEnabled = true
        self.isMultipleTouchEnabled = true

        self.addGestureRecognizer(panRecognizer)
        self.addGestureRecognizer(pinchRecognizer)
        self.addGestureRecognizer(rotateRecognizer)
    }
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    superview?.bringSubview(toFront: self)
}

Also in DragButton are the methods for handling the gestures, however I don't think my problem lies in there.

So to recap - I need a subclassed button (DragButton) to be instantiated programmatically, and have it react to all the 3 gestures. The issue with my code above is none of the gestures work with awakeFromNib, however they work faulty with layoutSubviews on the first tap, then each subsequent tap doubles up the velocity of the panning (hence the fault).

来源:https://stackoverflow.com/questions/40013332/getting-gestures-to-work-with-subclassed-uibutton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!