skip to content

In UIKit, a custom push animator grows a dish photo into its detail screen, but afterwards the app is stuck and Back does nothing; what is wrong, and how should the animator work?

level: seniorimportance: should knowfreq 32%

answer

  1. who tells UIKit the animation ended
  2. the transition context, not the views
  3. every path ends the same way
  4. add the to-view to containerView
  5. completeTransition with transitionWasCancelled

basics

~10 s

The animator never called completeTransition(_:) on its transition context, so UIKit never finished the push. An animator adds the incoming view to containerView, animates it, and ends every path with completeTransition(!transitionWasCancelled).

solid answer

~40 s

A custom push is two objects: the navigation controller's delegate returns an animator from `navigationController(_:animationControllerFor:from:to:)`, and the animator adopts `UIViewControllerAnimatedTransitioning` with `transitionDuration(using:)` and `animateTransition(using:)`. UIKit hands the animator a transition context; the header says every custom animation must call its `completeTransition(_:)` when it ends, and that call is what updates the view controller state at the end of the transition. If a branch skips it, such as an early `return` in a `guard`, the push never finishes and the screen stays stuck. A correct animator gets views with `view(forKey:)`, adds the to-view to `containerView`, animates to `finalFrame(for:)`, and calls `completeTransition(!transitionContext.transitionWasCancelled)` in the completion. On iOS 18 and later, `preferredTransition = .zoom { ... }` gives a system zoom with no animator at all.

code

swift · 40 lines
swift
import UIKit

final class DishGrowAnimator: NSObject, UIViewControllerAnimatedTransitioning {
    private let photoFrame: CGRect // the tapped photo, in window coordinates
    init(photoFrame: CGRect) { self.photoFrame = photoFrame }

    func transitionDuration(using transitionContext: (any UIViewControllerContextTransitioning)?) -> TimeInterval {
        0.35
    }

    func animateTransition(using transitionContext: any UIViewControllerContextTransitioning) {
        guard let toView = transitionContext.view(forKey: .to),
              let toVC = transitionContext.viewController(forKey: .to) else {
            transitionContext.completeTransition(false)
            return
        }
        let container = transitionContext.containerView
        let finalFrame = transitionContext.finalFrame(for: toVC)
        container.addSubview(toView) // the animator must put the incoming view in the container
        toView.frame = container.convert(photoFrame, from: nil)
        toView.clipsToBounds = true
        UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
            toView.frame = finalFrame
        }, completion: { _ in
            // Exactly one call, on every path, reporting whether the push really finished.
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
        })
    }
}

final class MenuViewController: UIViewController, UINavigationControllerDelegate {
    var tappedPhotoFrame: CGRect = .zero

    func navigationController(_ navigationController: UINavigationController,
                              animationControllerFor operation: UINavigationController.Operation,
                              from fromVC: UIViewController,
                              to toVC: UIViewController) -> (any UIViewControllerAnimatedTransitioning)? {
        operation == .push ? DishGrowAnimator(photoFrame: tappedPhotoFrame) : nil
    }
}

go deeper

for a junior

Recall that a custom transition needs an animator object, and that the animator must tell UIKit when it is done by calling completeTransition.

for a middle

Explain the roles: the navigation delegate picks the animator, the transition context supplies views and frames, and the animator works inside containerView.

for a senior

Trace every branch of animateTransition to one completeTransition call, report cancellation correctly, and add an interactive pop with UIPercentDrivenInteractiveTransition.

for a principal

Weigh a hand-written animator's maintenance against the iOS 18 zoom transition, and set when the team allows custom transitions at all given the deployment target.

## The pieces of a custom push UIKit lets you replace the standard slide of a navigation push or pop, and of a modal present or dismiss, with your own animation. For a **navigation** transition the pieces are: 1. The **navigation controller's delegate** implements `navigationController(_:animationControllerFor:from:to:)`. It receives the operation (`.push` or `.pop`) and both view controllers, and returns an animator or `nil` for the standard animation. 2. The **animator** adopts **`UIViewControllerAnimatedTransitioning`**: `transitionDuration(using:)` returns the duration, and `animateTransition(using:)` performs the animation. 3. UIKit builds a **transition context**, an object adopting `UIViewControllerContextTransitioning`, and passes it to the animator. It provides `containerView`, the views and view controllers for the `.from` and `.to` keys, their initial and final frames, and `transitionWasCancelled`. Modal presentations use a different hook: the presented view controller's `transitioningDelegate`, with `animationController(forPresented:presenting:source:)` and `animationController(forDismissed:)`. Returning an animator from the wrong delegate is a common reason a custom push never runs. ## The contract the animator must keep - Do the animation **inside `containerView`**, and add the incoming view to it yourself. - Get views with **`view(forKey:)`**. The header says animators should not touch a view controller's views directly, and a `nil` result means you should leave that view alone. - Animate to **`finalFrame(for:)`** for the incoming view controller; a non-zero final frame must be respected. - Call **`completeTransition(_:)`** when the transition ends or is cancelled, passing whether it really completed. The header says all custom animations must invoke it and that it updates the view controller state at the end of the transition. From iOS 17 it is safe to call more than once; only the first call counts. ## Why the app is stuck The usual bug is a branch that returns without calling `completeTransition(_:)`: a `guard` that fails because a snapshot view was missing, a completion block that runs only when `finished` is true, or an animation that is never started. UIKit still considers the push in flight: the call that updates the view controller state at the end of the transition never happened. The dish view may be visible, yet the navigation interface doesn't behave until it does. The fix is structural: **every path ends in exactly one `completeTransition(_:)`**, including the failure path, which can pass `false`. The second bug is passing `true` unconditionally. For an interactive transition the user can cancel halfway; pass `!transitionContext.transitionWasCancelled` so a cancelled pop leaves the stack as it was. ## Making it interactive To let the user drag a pop, also implement `navigationController(_:interactionControllerFor:)` and return a **`UIPercentDrivenInteractiveTransition`** while a pan gesture is driving the pop, `nil` otherwise. The pan handler calls `update(_:)` with the fraction complete, then `finish()` or `cancel()`. The percent-driven class scrubs the animations the animator created, and the animator's `completeTransition(_:)` call still ends the transition. For an animator that must be interrupted mid-flight, `interruptibleAnimator(using:)` can return a `UIViewPropertyAnimator`. ## The same contract for modal transitions A custom **presentation** uses the presented view controller's `transitioningDelegate` instead of the navigation delegate, and the same animator protocol. - `animationController(forPresented:presenting:source:)` and `animationController(forDismissed:)` return the animators; `interactionControllerForDismissal(using:)` adds a drag to dismiss. - `presentationController(forPresented:presenting:source:)` returns a custom `UIPresentationController` subclass for chrome such as a dimming view, used when `modalPresentationStyle` is `.custom`. - `transitioningDelegate` is a **weak** property: an object created inline and assigned to it can be deallocated before the presentation, and the custom animation silently never runs. Keep a strong reference, usually in the presenter. ## The iOS 18 zoom transition From **iOS 18**, a view controller's `preferredTransition` accepts **`.zoom(options:sourceViewProvider:)`**. Set it on the dish screen before pushing, and return the tapped photo's view from the provider; UIKit zooms from that view into the pushed screen and back. The provider may be called more than once, so it should look the source view up again rather than capture a stale one. `UINavigationController` supports `.zoom`; a transition the container doesn't support may be ignored, because `preferredTransition` is only a preference. For apps that deploy to iOS 17, keep the custom animator behind `if #available(iOS 18.0, *)`. ## Review checklist - The delegate returns an animator only for the operations it animates. - The to-view is added to `containerView` before animating. - No path leaves `animateTransition(using:)` without a scheduled `completeTransition(_:)`. - Cancellation is reported through `transitionWasCancelled`.

  • How do you make the pop follow the user's finger?
    Implement navigationController(_:interactionControllerFor:) and return a UIPercentDrivenInteractiveTransition while a pan gesture is driving the pop. The pan handler calls update(_:) with the fraction complete, then finish() or cancel() when the finger lifts. The animator's completion still calls completeTransition(!transitionWasCancelled), so a cancelled drag leaves the dish screen in place.
  • When would you use the iOS 18 zoom transition instead of writing an animator?
    Whenever the deployment target allows it and the effect you want is a zoom from a source view. Setting preferredTransition = .zoom with a source-view provider gets the system animation without a delegate or animator to maintain. Keep a custom animator only for effects zoom can't express, or behind an availability check for iOS 17 devices.

  • Calls completeTransition(true) even when the interactive transition was cancelled.
  • Returns early from animateTransition without calling completeTransition.
  • Forgets to add the incoming view to the transition's container view.
  • Returns a push animator from the view controller's transitioningDelegate.
  • Believes the zoom preferredTransition works on an iOS 17 device.

Assumes the iOS 27.1 SDK; the system zoom preferredTransition is iOS 18, and from iOS 17 extra completeTransition(_:) calls are ignored after the first.