Junior — Middle
Hoe kun je een aangepaste animatie-overgang implementeren bij het wisselen tussen schermen in een Navigation Controller?
sobes.tech AI
Antwoord van AI
Om een aangepaste animatie-overgang tussen schermen in UINavigationController te implementeren, moet je de protocollen UIViewControllerAnimatedTransitioning en UINavigationControllerDelegate gebruiken.
-
Maak een klasse die
UIViewControllerAnimatedTransitioningimplementeert, waarin je de animatielogica beschrijft in de methoden:transitionDuration(using:)— duur van de animatieanimateTransition(using:)— de eigenlijke overgangsanimatie
-
Stel als delegate van UINavigationController een object in dat
UINavigationControllerDelegateimplementeert, en in de methode:func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { // retourneer je animatieobject return customAnimator }
Voorbeeld van een eenvoudige aangepaste 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)
}
}
}