Sobes.tech
Junior — Middle

Wie kann man eine eigene animierte Übergangsanimation beim Wechsel zwischen Bildschirmen in einem Navigation Controller implementieren?

sobes.tech KI

Antwort von AI

Um eine eigene Animationstransition zwischen Bildschirmen in UINavigationController zu implementieren, müssen Sie die Protokolle UIViewControllerAnimatedTransitioning und UINavigationControllerDelegate verwenden.

  1. Erstellen Sie eine Klasse, die UIViewControllerAnimatedTransitioning implementiert, in der Sie die Animationslogik in den Methoden beschreiben:

    • transitionDuration(using:) — Dauer der Animation
    • animateTransition(using:) — die eigentliche Übergangsanimation
  2. Legen Sie ein Objekt, das UINavigationControllerDelegate implementiert, als Delegierten des UINavigationController fest, und in der Methode:

    func navigationController(_ navigationController: UINavigationController, 
                              animationControllerFor operation: UINavigationController.Operation, 
                              from fromVC: UIViewController, 
                              to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        // gibt Ihr Animationsobjekt zurück
        return customAnimator
    }
    

Beispiel eines einfachen benutzerdefinierten Animators:

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)
        }
    }
}