Sobes.tech
Junior — Middle

Kā var īstenot savu animēto pāreju, pārejot starp ekrāniem Navigation Controller?

sobes.tech AI

Atbilde no AI

Lai īstenotu savu animācijas pāreju starp ekrāniem UINavigationController, ir jāizmanto protokoli UIViewControllerAnimatedTransitioning un UINavigationControllerDelegate.

  1. Izveidojiet klasi, kas realizē UIViewControllerAnimatedTransitioning, kurā aprakstāt animācijas loģiku:

    • transitionDuration(using:) — animācijas ilgums
    • animateTransition(using:) — pati pārejas animācija
  2. Uzstādiet UINavigationController delegātu kā objektu, kas realizē UINavigationControllerDelegate, un metodē:

    func navigationController(_ navigationController: UINavigationController, 
                              animationControllerFor operation: UINavigationController.Operation, 
                              from fromVC: UIViewController, 
                              to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        // atgriež savu animācijas objektu
        return customAnimator
    }
    

Vienkārša pielāgota animatora piemērs:

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