Sobes.tech
Junior — Middle

How can you implement a custom animated transition when switching between screens in a Navigation Controller?

sobes.tech AI

Answer from AI

To implement a custom animated transition between screens in UINavigationController, you need to use the protocols UIViewControllerAnimatedTransitioning and UINavigationControllerDelegate.

  1. Create a class that implements UIViewControllerAnimatedTransitioning, where you define the animation logic in the methods:

    • transitionDuration(using:) — the duration of the animation
    • animateTransition(using:) — the transition animation itself
  2. Set an object implementing UINavigationControllerDelegate as the delegate of UINavigationController, and in the method:

    func navigationController(_ navigationController: UINavigationController, 
                              animationControllerFor operation: UINavigationController.Operation, 
                              from fromVC: UIViewController, 
                              to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        // return your animation object
        return customAnimator
    }
    

Example of a simple custom animator:

class CustomAnimator: NSObject, UIViewControllerAnimatedTransitioning {
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.3
    }

    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        guard let toView = transitionContext.view(forKey: .to) else {
            transitionContext.completeTransition(false)
            return
        }
        let container = transitionContext.containerView
        toView.alpha = 0
        container.addSubview(toView)

        UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
            toView.alpha = 1
        }) { finished in
            transitionContext.completeTransition(finished)
        }
    }
}
How can you implement a custom animated transition… - sobes.tech