Junior — Middle
Hogyan lehet saját animált átmenetet megvalósítani a képernyők közötti váltás során egy Navigation Controller-ben?
sobes.tech MI
Válasz az MI-től
A UINavigationController-ben képernyők közötti egyedi animált átmenet megvalósításához használja a UIViewControllerAnimatedTransitioning és UINavigationControllerDelegate protokollokat.
-
Hozzon létre egy osztályt, amely megvalósítja a
UIViewControllerAnimatedTransitioningprotokollt, és írja le az animáció logikáját a következő módszerekben:transitionDuration(using:)— az animáció időtartamaanimateTransition(using:)— maga az átmenet
-
Állítsa be a UINavigationController delegátusát egy olyan objektumra, amely megvalósítja a
UINavigationControllerDelegate-t, és a következő módszerben:func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { // adja vissza az animációs objektumot return customAnimator }
Egyszerű példája egy egyedi animátornak:
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)
}
}
}