I have a SpringButton which I want to drag. This is my code:
var gesture = UIPanGestureRecognizer(target: self, action: #selector(userDragged))
card.addGestureRecognizer(gesture)
var cardIsCurrentlyMoving = false
func userDragged(gesture: UIPanGestureRecognizer){
if !cardIsCurrentlyMoving{
if let button = gesture.view as? SpringButton {
if gesture.state == .began {
print("begon")
cardIsCurrentlyMoving = true
startPosition = button.center
} else if gesture.state == .changed {
print("changed")
} else if gesture.state == .ended{
print("ended")
cardIsCurrentlyMoving = false
}
}
}
}
The function gets called, and the state gets changed to .began
. However, when trying to move the button nothing happens. This is because cardIsCurrentlyMoving
is set to true in .began
, but never back to false, because gesture.state .changed
and .ended
never gets called.
When I release my finger and touch the button again, nothing happens as well. Why does UIPanGestureRecognizer
not executes .changed
and .ended
?
Thanks.
I think you need to check your if statement
if !cardIsCurrentlyMoving{
}
Pan Gesture continuously calls method with changed state. So userDragged func called continuously but just because of your above if statement, control doesn't go inside if statement.
So i'll suggest to use this, instead of yours.
func userDragged(gesture: UIPanGestureRecognizer){
if let button = gesture.view as? SpringButton {
if gesture.state == .began {
print("begon")
cardIsCurrentlyMoving = true
startPosition = button.center
} else if gesture.state == .changed {
print("changed")
} else if gesture.state == .ended{
print("ended")
cardIsCurrentlyMoving = false
}
}
}