skip to content

View Controller Lifecycle

View controller callbacks from viewDidLoad to viewDidDisappear, and the app and scene launch sequence through sceneDidEnterBackground. Setup in the wrong callback causes repeated work or leaks.

on this pageshow

explore

questions

6

In UIKit, in what order do a view controller's callbacks run from loadView() to viewDidDisappear(_:), and what work belongs in each?

level: juniorimportance: must knowfreq 85%

answer

  1. once per view versus every appearance
  2. the view is created on first access
  3. geometry is valid only inside the window
  4. viewIsAppearing(_:) sits between will and did
  5. start on appear, stop on the matching disappear

basics

~10 s

UIKit calls loadView() and viewDidLoad() once, when the view is first needed, then viewWillAppear(:), viewIsAppearing(:) and viewDidAppear(:) on every appearance and viewWillDisappear(:) and viewDidDisappear(_:) on every disappearance. One-time setup belongs in viewDidLoad().

solid answer

~40 s

A view controller creates its view lazily: the first read of `view` calls `loadView()`, and `viewDidLoad()` follows once the hierarchy exists, so building subviews, constraints and wiring goes there. Every time the screen comes on screen UIKit calls `viewWillAppear(_:)` (not yet in the hierarchy), `viewIsAppearing(_:)` (in the hierarchy, laid out, traits and safe area valid) and `viewDidAppear(_:)` (after the transition animation finishes). Leaving, whether popped, dismissed or covered by a pushed screen, it calls `viewWillDisappear(_:)` and then `viewDidDisappear(_:)`. Per-appearance work goes in the appear callbacks and is undone in the matching disappear one, such as starting a camera preview in `viewDidAppear(_:)` and stopping it in `viewDidDisappear(_:)`. Appearance overrides must call `super`; a custom `loadView()` must not.

code

swift · 27 lines
swift
import UIKit

final class CallViewController: UIViewController {
    private let controlsBar = UIStackView()

    override func loadView() {
        view = UIView()                   // no super: this replaces the default view
    }

    override func viewDidLoad() {
        super.viewDidLoad()               // once: build and wire the hierarchy
        view.addSubview(controlsBar)
    }

    override func viewIsAppearing(_ animated: Bool) {
        super.viewIsAppearing(animated)   // each appearance: traits and geometry are valid
        controlsBar.isHidden = traitCollection.verticalSizeClass == .compact
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)     // on screen: start what the user should see begin
    }

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)  // gone: stop what viewDidAppear(_:) started
    }
}

go deeper

for a junior

Recite the order from loadView() to viewDidDisappear(_:), say which run once and which run on every appearance, and put one-time setup in viewDidLoad().

for a middle

Explain what is true in each callback, why viewIsAppearing(_:) is the safe place for trait and geometry work, and how isMovingFromParent separates a pop from a cover.

for a senior

Show the symmetry rule in review: every start on the appear side has a stop on the matching disappear side, and nothing repeatable lives in viewDidLoad() or layout callbacks.

for a principal

Set a team convention for which callback owns which kind of work, so reviewers can spot a camera, observer or timer started without its matching stop.

## Two kinds of callback A `UIViewController` sends its subclass two kinds of lifecycle message, and most bugs in this area come from putting work in the wrong kind: - **Load callbacks** run when the view controller's root view is created. In practice that is **once** per view controller: since iOS 6 a memory warning no longer releases a loaded view by default, and the old `viewDidUnload()` is deprecated and unavailable in Swift. - **Appearance callbacks** run **every time** the view comes on screen or leaves it: on first presentation, when a pushed screen is popped off it, when a covering presentation is dismissed, and when the user switches back to its tab. ## Loading the view The `view` property is lazy. Its getter calls `loadView()` if no view has been set yet, so nothing is built until something reads `view` (presenting, pushing, adding the controller as a child, or your own `loadViewIfNeeded()`). 1. **`loadView()`** creates the root view. If the controller has a nib or storyboard scene, the default implementation loads it; otherwise it makes a plain `UIView`. Override it only to build the root view in code: assign your view to `view` and **do not call `super`**. Never override it when the view comes from Interface Builder, and never call it yourself. 2. **`viewDidLoad()`** runs once the hierarchy exists, whether it came from a nib or from `loadView()`. This is the place for one-time setup: adding subviews, activating constraints, registering cells, wiring targets and data sources. `isViewLoaded` and `viewIfLoaded` let code ask whether the view exists without forcing it to load. ## Appearing and disappearing | Callback | When UIKit calls it | Typical work | |---|---|---| | `viewWillAppear(_:)` | before the view joins the hierarchy, before animations are set up | alongside animations with the `transitionCoordinator`; balanced registrations that do not depend on traits | | `viewIsAppearing(_:)` | after the view is added and laid out, once per appearance | updating views from traits, size and safe area; scrolling to a selected item | | `viewDidAppear(_:)` | after the transition animation completes | starting work the user should see begin: a camera preview, a hide-controls timer | | `viewWillDisappear(_:)` | before the view is removed, before animations are set up | committing edits, resigning first responder | | `viewDidDisappear(_:)` | after the view is fully dismissed, covered or hidden | stopping what the appear side started | `viewWillAppear(_:)` and `viewIsAppearing(_:)` run inside the same Core Animation transaction, so changes made in either are seen at the same moment. The difference is what is true when they run: in the first, the view is not yet in a window and its traits and geometry may be stale; in the second, all of them are valid. Inside the disappear callbacks, `isMovingFromParent` and `isBeingDismissed` tell a screen that is going away for good from one that is only covered by a pushed screen, which receives the same pair of calls. ## Pairing the work The rule that keeps the appearance callbacks honest is **symmetry**. Anything started on the appear side must be stopped on the disappear side, because the pair can run many times for one controller. A call screen that starts its camera preview in `viewDidAppear(_:)` stops it in `viewDidDisappear(_:)`, or the camera keeps running under the next screen. A notification observer added in `viewWillAppear(_:)` is removed in `viewDidDisappear(_:)`. One-time objects, such as the subviews and the data source, are built in `viewDidLoad()` and never rebuilt. Overrides of the appearance callbacks must call `super` at some point, and `viewDidLoad()` overrides call it by convention; the exception is a custom `loadView()`, which must not. ## What is not in the sequence - **Layout callbacks**, `viewWillLayoutSubviews()` and `viewDidLayoutSubviews()`, are not steps in this order. They run whenever the view lays out its subviews, which can be several times during one transition and at any moment while the screen is visible. - **Size and trait changes** arrive through `viewWillTransition(to:with:)` and trait-change registrations, without any appearance callback. - **`didReceiveMemoryWarning()`** is sent when the app receives a memory warning; an override frees caches it can rebuild and calls `super`. - App-level and window-level events, such as moving to the background, come from the scene delegate, not from these callbacks: a screen that is on screen when the app is backgrounded receives no `viewWillDisappear(_:)`.

  • In UIKit, does pushing a second screen onto a navigation stack send the first screen any callbacks?
    Yes. The covered screen receives `viewWillDisappear(_:)` and `viewDidDisappear(_:)`, and when the second screen is popped it receives `viewWillAppear(_:)`, `viewIsAppearing(_:)` and `viewDidAppear(_:)` again. `viewDidLoad()` does not run again, because its view was never released. Checking `isMovingFromParent` inside the disappear callbacks tells being covered from being popped.
  • In UIKit, what happens if code reads a view controller's view property in its initializer?
    Reading `view` forces `loadView()` and then `viewDidLoad()` immediately, inside the initializer, before the caller has had a chance to set the properties that `viewDidLoad()` may depend on. The view also loads even if the screen is never shown. Code that only needs to know whether the view exists should read `isViewLoaded` or `viewIfLoaded` instead.

A shop builds its fittings once when it opens for the first time, but unlocks the door, switches on the lights and starts the till every morning, and reverses each of those every evening. viewDidLoad() is the fitting-out; the appear and disappear callbacks are the daily opening and closing.

  • viewDidLoad() runs every time the screen comes back on screen
  • A custom loadView() should start by calling super.loadView()
  • viewWillAppear(_:) is the place to read the final frame and safe area
  • A covered screen gets no callbacks when another screen is pushed over it
  • Backgrounding the app sends the visible screen viewWillDisappear(_:)
open as a page

In a scene-based UIKit app, which UISceneDelegate callbacks fire when a call screen is interrupted or backgrounded, and why don't the app delegate's equivalents fire?

level: middleimportance: must knowfreq 65%

basics

~10 s

An interruption calls sceneWillResignActive(:); going to the background calls sceneWillResignActive(:) then sceneDidEnterBackground(:); returning calls sceneWillEnterForeground(:) then sceneDidBecomeActive(_:). With scenes enabled UIKit calls these instead of the app delegate's methods, which iOS 26 deprecated.

open as a page

In UIKit, how should a video call screen rearrange its participant grid on rotation and iPad window resizing, using viewWillTransition(to:with:) and trait-change registration?

level: middleimportance: should knowfreq 58%

basics

~10 s

Override viewWillTransition(to:with:) for the new size, call super, and animate the grid change inside the coordinator's animate(alongsideTransition:completion:). For size-class changes, register in viewDidLoad() with registerForTraitChanges(:handler:) (iOS 17), which replaced traitCollectionDidChange(:).

open as a page

In UIKit, why is viewIsAppearing(_:) better than viewWillAppear(_:) for work that needs the view's size or traits, and which iOS releases can call it?

level: middleimportance: should knowfreq 55%

basics

~20 s

viewWillAppear(:) runs before the view joins the hierarchy, so traits, size and safe area may be stale; viewIsAppearing(:) runs just after, once per appearance, with all of them valid. It shipped in the iOS 17 SDK and back-deploys to iOS 13.

open as a page

In UIKit, a call screen embeds participant tiles as child view controllers, but each tile's didMove(toParent:) setup never runs and removed tiles stay in memory; what is wrong?

level: seniorimportance: should knowfreq 45%

basics

~20 s

addChild(_:) calls the child's willMove(toParent:) but not didMove(toParent:), which the container must call after adding the child's view. Removing only the view leaves the child in children, still alive; removal needs willMove(toParent: nil), removing the view, then removeFromParent().

open as a page

A UIKit call screen adds participant tiles in viewDidLayoutSubviews() and starts a repeating hide-controls timer in viewWillAppear(_:); why do tiles duplicate and controls hide erratically?

level: seniorimportance: should knowfreq 60%

basics

~20 s

viewDidLayoutSubviews() runs on every layout pass, not once, so tiles are added again on each rotation or inset change. viewWillAppear(_:) runs on every appearance, so each return schedules another timer while the old ones keep firing.

open as a page