Junior — Middle
Cum se poate implementa o tranziție animată personalizată la trecerea între ecrane într-un Navigation Controller?
sobes.tech AI
Răspuns de la AI
Pentru a implementa o tranziție animată personalizată între ecrane în UINavigationController, trebuie să utilizați protocoalele UIViewControllerAnimatedTransitioning și UINavigationControllerDelegate.
-
Creați o clasă care implementează
UIViewControllerAnimatedTransitioning, unde descrieți logica animației în metodele:transitionDuration(using:)— durata animațieianimateTransition(using:)— animația propriu-zisă a tranziției
-
Stabiliți ca delegat al UINavigationController un obiect care implementează
UINavigationControllerDelegate, și în metoda:func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { // returnați obiectul dvs. de animație return customAnimator }
Exemplu de animator personalizat simplu:
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)
}
}
}