Sobes.tech
Junior — Middle

Jak lze implementovat vlastní animovaný přechod při přechodu mezi obrazovkami v Navigation Controlleru?

sobes.tech AI

Odpověď od AI

Chcete-li implementovat vlastní animovaný přechod mezi obrazovkami v UINavigationController, musíte použít protokoly UIViewControllerAnimatedTransitioning a UINavigationControllerDelegate.

  1. Vytvořte třídu, která implementuje UIViewControllerAnimatedTransitioning, a v metodách popište logiku animace:

    • transitionDuration(using:) — délka trvání animace
    • animateTransition(using:) — samotná animace přechodu
  2. Nastavte jako delegáta UINavigationController objekt, který implementuje UINavigationControllerDelegate, a v metodě:

    func navigationController(_ navigationController: UINavigationController, 
                              animationControllerFor operation: UINavigationController.Operation, 
                              from fromVC: UIViewController, 
                              to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        // vraťte svůj animační objekt
        return customAnimator
    }
    

Příklad jednoduchého vlastního animátoru:

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