问题
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