Sobes.tech
Junior — Middle

W jaki sposób można zaimplementować własną animowaną przejście podczas przełączania ekranów w Navigation Controller?

sobes.tech AI

Odpowiedź od AI

Aby zaimplementować własne animowane przejście między ekranami w UINavigationController, należy użyć protokołów UIViewControllerAnimatedTransitioning i UINavigationControllerDelegate.

  1. Utwórz klasę implementującą UIViewControllerAnimatedTransitioning, w której opiszesz logikę animacji w metodach:

    • transitionDuration(using:) — czas trwania animacji
    • animateTransition(using:) — sama animacja przejścia
  2. Ustaw jako delegata UINavigationController obiekt implementujący UINavigationControllerDelegate, a w metodzie:

    func navigationController(_ navigationController: UINavigationController, 
                              animationControllerFor operation: UINavigationController.Operation, 
                              from fromVC: UIViewController, 
                              to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        // zwróć swój obiekt animacji
        return customAnimator
    }
    

Przykład prostego niestandardowego animatora:

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