SwiftUI View Lifecycle
An iOS and macOS app that demonstrates how different SwiftUI constructs and SwiftUI container views affect:
- the lifetime of
@State
- the firing of events such as
onAppear
andonDisappear
By Ole Begemann, 2022
SwiftUI View Lifecycle app on GitHub
My article introducing the app: Understanding View Lifecycles (2022-12-15)
Usage
- Open the project in Xcode.
- Run the app on the iOS simulator, an iOS device, or on macOS.
- Click through the list of examples and observe the timestamps when certain lifecycle events happened.
Requirements
Requires iOS 16 or macOS 13.
Screenshots
iPhone
iPad
Mac
LifecycleMonitor
view
The All examples use one or more LifecycleMonitor
views as their content. The view below tracks its lifecycle events and displays them as constantly-updating timestamps. For example, this view got created 1:26 minutes ago, which is also when its @State
got created. Its .onAppear
and .onDisappear
actions were last called 15 and 47 seconds ago, respectively:
As you interact with the app, e.g. by scrolling through a List
, you’ll see these timestamps update (or not, depending on the container view). Pay special attention to resets of the @State
field because this means that the view got destroyed and recreated, losing all of its internal state.
The view’s background color is set to a random color when its @State
is created, so color changes are another indication that the view identity has changed.