Search code examples
iosswiftuipangesturerecognizer

Pan Gesture completion handler getting called immediately


I'm animating a view to move as the user pans the screen. I have kept a threshold after which the view will animate to a default position.

The problem currently is that the completion handler of the animate method which resets the view to a position is called before the duration. The animation seems to be happening abruptly instead of over a duration of time.

// Pan gesture selector method
@objc func panAction(for panGesture: UIPanGestureRecognizer) {
    switch panGesture.state {
    case .began:
    //Began code
    case changed:
    if (condition) {
       print("IF")
       //Change constraint constant of customView
       animate(view: customView)
    } else if (condition) {
       print("ELSE IF")
       //Change constraint constant of customView
       animate(view: customView)
    } else {
       //Change constraint constant of customView
       print("ELSE")
       view.layoutIfNeeded()
    }
    case .ended:
    //Ended code
    default:
    break
    }
}

The animate method:

func animate(view: UIView) {
    UIView.animate(withDuration: 3, delay: 0, options: .curveEaseOut, animations: {
        view.layoutIfNeeded()
    }, completion: { (finished) in
        if finished {
            flag = false
        }
    })
}

The flag is being set immediately rather than after 3 seconds.

The o/p i get while panning and crossing threshold.

ELSE

ELSE

ELSE

ELSE

IF

Edit: I am an idiot. I did not call layoutIfNeeded() on the superView.


Solution

  • I solved this. I was not calling layoutIfNeeded on the superview.