Describe the process and considerations for implementing a custom transition between two UIViewControllers.
Instruction: Explain how you would create a custom animated transition between two UIViewControllers, detailing the steps involved and any specific protocols or methods you would utilize. Discuss how you would ensure the transition is smooth and performs well across different iOS devices.
Updated
Official answer
For a modal custom transition, provide a UIViewControllerTransitioningDelegate that supplies a UIViewControllerAnimatedTransitioning animator for presentation and, where needed, dismissal. Retain the delegate for the transition's lifetime: the presented controller's transitioningDelegate reference is weak. A custom presentation layout may additionally need UIPresentationController; a navigation push/pop uses UINavigationControllerDelegate instead.
The animator implements transitionDuration(using:) and animateTransition(using:). Obtain the from/to views, containerView and destination's final frame from the supplied transition context rather than assuming full-screen geometry. Insert the correct destination view into the container, set its initial state and animate toward the final state. On completion, inspect transitionWasCancelled and call completeTransition with the appropriate success value. Restore temporary transforms/alpha and remove only the views that should disappear on that success or cancellation path.
For gesture-driven interaction, a percent-driven interactive transition can update progress and then finish or cancel. Test cancellation midway as carefully as successful completion; an animation looking finished is not sufficient if UIKit has never been told the transition completed. Use the transition coordinator for related changes that should track the system's timing.
Keep layout and expensive rendering work out of each animation frame, prepare needed assets and profile hitches on target devices and refresh rates. Test rotation/resizing, compact and regular layouts, repeated presentation/dismissal, VoiceOver focus and Reduce Motion. Prefer a simpler fade or suitable system behavior when motion/accessibility settings warrant it; do not promise a universal 60-fps target across devices.
Custom transition lifecycle, Transition delegate lifetime, Performance measurement
Related Questions
-
medium
-
medium
-
hard
-
hard