I have a custom animation transition for push and pop events in a UINavigationController stack and I want to apply that custom animation only to specific push events--for example, when pushing RandomViewController44() or popping RandomViewController27()--not every push and pop in the stack. Is that done in the UINavigationControllerDelegate, in the animator object, or at the point of push/pop?
The delegate
extension BaseViewController: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
switch operation {
case .push:
return InAnimator()
case .pop:
return OutAnimator()
default:
return nil
}
}
}
The animator object
class InAnimator: NSObject, UIViewControllerAnimatedTransitioning {
let animationDuration = 0.5
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return animationDuration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let screenHeight = UIScreen.main.bounds.height
let screenWidth = UIScreen.main.bounds.width
let containerView = transitionContext.containerView
let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)
containerView.addSubview(toViewController!.view)
toViewController!.view.frame = CGRect(x: screenWidth * -1, y: 0, width: screenWidth, height: screenHeight)
UIView.animate(withDuration: animationDuration, animations: {
toViewController!.view.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)
}, completion: { finished in
let cancelled = transitionContext.transitionWasCancelled
transitionContext.completeTransition(!cancelled)
})
}
}
The call to push
func pushVC() {
navigationController?.pushViewController(randomViewController44(), animated: true)
}