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.
-
Create a class that implements
UIViewControllerAnimatedTransitioning, where you define the animation logic in the methods:transitionDuration(using:)— the duration of the animationanimateTransition(using:)— the transition animation itself
-
Set an object implementing
UINavigationControllerDelegateas 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)
}
}
}