Observe how different SwiftUI container views affect state and lifecycle events (onAppear, onDisappear).
An iOS and macOS app that demonstrates how different SwiftUI constructs and SwiftUI container views affect:
@State
onAppear
and onDisappear
By Ole Begemann, 2022
SwiftUI View Lifecycle app on GitHub
My article introducing the app: Understanding View Lifecycles (2022-12-15)
Requires iOS 16 or macOS 13.
LifecycleMonitor
viewAll 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.