Skip to the workspace
Pebellslearn by building
UIKit  ›  Lesson

The View Controller Lifecycle

ViewController Lifecycle 12 minUIKit calls viewDidLoad once when a view controller's view loads, and viewWillAppear, viewDidAppear, viewWillDisappear and viewDidDisappear each time it comes on or leaves the screen.

ios / The View Controller Lifecycle

Explore each scene at your own pace.

01 · The rule

The rule

The View Controller Lifecycle

TrailLog's hike list is supposed to show a newly saved hike when you return to it. It doesn't — until you restart the app. The data was saved fine; the list just refreshed at the wrong moment in its lifecycle.

The rule

viewDidLoad happens once; the appear methods happen every time.

A view controller (UIViewController) manages one screen: it owns a root view, fills it with subviews, and responds to events. UIKit calls its lifecycle methods in a fixed order:

  1. viewDidLoad() — the view has been created and loaded into memory. Called once per controller. One-time setup: add subviews, configure the table, set the title.
  2. viewWillAppear(_:) — about to come on screen. Called every time it appears, including when the user comes back to it. Refresh data that may have changed.
  3. viewIsAppearing(_:) (newer iOS) and viewDidLayoutSubviews() — sizes are now known. Adjust anything that depends on final geometry.
  4. viewDidAppear(_:) — fully on screen. Start animations, begin tracking, log a screen view.
  5. viewWillDisappear(_:) — about to leave. Stop timers, save edits in progress.
  6. viewDidDisappear(_:) — gone from the screen. Release things only needed while visible.
final class HikeListViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "My Hikes"
        view.addSubview(tableView)            // once
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        hikes = store.allHikes()              // every time
        tableView.reloadData()
    }
}

Always call super first in these overrides; UIKit's own work depends on it.

Note what not to do in viewDidLoad: rely on final sizes. The view exists, but it may not have its on-screen size yet.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.