Search code examples
iosswifttransitioninteractive

Drag-to-dismiss interactive transition out of sync with pan gesture


I am trying to implement a custom drag-to-dismiss interactive transition, using UIViewControllerAnimatedTransitioning and UIPercentDrivenInteractiveTransition.

Here is the animator code for dismissing, it just moves the view down completely out from the frame:

final class SheetDismissAnimator: NSObject, UIViewControllerAnimatedTransitioning {

    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        0.5
    }

    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        guard let fromVC = transitionContext.viewController(forKey: .from) else { return }

        UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
            fromVC.view.frame.origin.y = transitionContext.containerView.frame.height
        }, completion: { _ in
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
        })
    }

}

And here is the code for the modal view controller I am trying to dismiss, which has the pan gesture recognizer attached to it:

final class ModalViewController: UIViewController {

    private let customTransitionDelegate = SheetTransitioningDelegate()
    private var interactionController: UIPercentDrivenInteractiveTransition?

    init() {
        super.init(nibName: nil, bundle: nil)

        modalPresentationStyle = .custom
        transitioningDelegate = customTransitionDelegate
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .red
        view.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(handleGesture(_:))))
    }

    @objc func handleGesture(_ gesture: UIPanGestureRecognizer) {
        let translate = gesture.translation(in: view)
        let percent   = translate.y / view.bounds.height

        switch gesture.state {
        case .began:
            interactionController = UIPercentDrivenInteractiveTransition()
            customTransitionDelegate.interactionController = interactionController
            dismiss(animated: true)
        case .changed:
            interactionController?.update(percent)
        case .cancelled:
            interactionController?.cancel()
        case .ended:
            let velocity = gesture.velocity(in: gesture.view)
            if percent > 0.5 || velocity.y > 700 {
                interactionController?.finish()
            } else {
                interactionController?.cancel()
            }
            interactionController = nil
        default:
            break
        }

    }
}

The relevant part I believe is the handleGesture(_ gesture: UIPanGestureRecognizer) function, which calculates the percentage for advancing the animation. Pasted the whole code for clarity.

I would expect the animation to follow the pan gesture linearly, but this is what happens instead:

https://media.giphy.com/media/Wn6kAgngfHeynjhAbm/giphy.gif


Solution

  • I solved the issue by switching to UIViewPropertyAnimator:

    final class SheetDismissAnimator: NSObject, UIViewControllerAnimatedTransitioning {
    
        func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
            0.5
        }
    
        func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
            let propertyAnimator = UIViewPropertyAnimator(duration: transitionDuration(using: transitionContext),
                                                      timingParameters: UISpringTimingParameters(dampingRatio: 1))
            propertyAnimator.addAnimations {
                switch self.type {
                case .presented:
                    guard let toVC = transitionContext.viewController(forKey: .to) else { break }
                    toVC.view.frame = transitionContext.finalFrame(for: toVC)
                case .dismissed:
                    transitionContext.view(forKey: .from)?.frame.origin.y = transitionContext.containerView.frame.maxY
                }
            }
            propertyAnimator.addCompletion { _ in
                transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
            }
    
            propertyAnimator.startAnimation()
        }
    
    }
    

    I also added the following into my gesture handling code, which is a basic attempt at transfering the gesture's velocity to the animation speed.

    case .ended:
        if percent > 0.45 || velocity.y > 700 {
            interactor.timingCurve = UICubicTimingParameters(animationCurve: .linear)
            interactor.completionSpeed = max(1, (view.frame.height * (1 / interactor.duration) / velocity.y))
            interactor.finish()
        } else {
            interactor.cancel()
        }
        isInteractive = false