So I found out how to make a button draggable using the UIPanGestureRecognizer. But the only way I know how to do it is by storing and dragging the button by the center. The problem with this is if you try and drag the button from a corner, the button instantly shifts from the corner to the center. What I'm looking for is a solution that would keep my finger on a selected place while moving without instantly locking onto the center.
The code I'm currently using:
func buttonDrag(pan: UIPanGestureRecognizer) {
print("Being Dragged")
if pan.state == .began {
print("panIF")
buttonCenter = button.center // store old button center
}else {
print("panELSE")
let location = pan.location(in: view) // get pan location
button.center = location // set button to where finger is
}
}
Thanks in advance.
This can be done at least in two different ways, one using
GestureRecognizer
your question way and other way is subclassing theUIView
and implementing thetouchesBegan
,touchesMoved
,touchesEnded
,touchesCancelled
in general will work for any UIView subclass can beUIButton
orUILabel
orUIImageView
etc...In your way, using
GestureRecognizer
I make a few changes you still require a var to keep the originCGPoint
of the touch in yourUIButton
so we get the touch position relative to the UIButton and when the drag continue adjust the UIButton origin according to the origin touch position and the positions of the movementMethod 1 GestureRecognizer
Method 2 UIView subclass in this case UIButton subclass
Use this
UIButton
subclassResult
Hope this helps you