Fate Riddle Fate Riddle - 5 months ago 7
iOS Question

A pan gesture without setTranslation strange behaviour

My code:

@IBAction func handlePan(gesture: UIPanGestureRecognizer) {
let transition = gesture.translationInView(self.view)
switch gesture.state{
case .Changed:
if let view = gesture.view {
view.center = CGPoint(x: view.center.x + transition.x, y: view.center.y + transition.y)
gesture.setTranslation(CGPointZero, inView: self.view)


So I can drag a big button in the screen around. Everything works find till I comment out
gesture.setTranslation(CGPointZero, inView: self.view)

I thought that one line of code only tells the app to remember the last position of the button on screen and move from there next time, but...

Then I ran the project again on a simulator, when I clicked on that button and tried to move a bit, the button just flew in the same direction and disappeared off screen, why?


As you pan around, the transition value is from where you first began the gesture.

Look at how you move the button. You just keep adding the larger and larger transition to each updated center. What you need to do is add the latest transition to the center as it was when the pan gesture was first recognized.

So either reset the translation (like in your posted code), or save the original center of the button when the gesture's state is .Began and apply the translation to the original center value.