< How to hide the label of a Picker, Stepper, Toggle, and more using labelsHidden() | How to respond to view lifecycle events: onAppear() and onDisappear() > |
Updated for Xcode 14.2
SwiftUI provides a scenePhase
environment key that is automatically updated as your app moves between the foreground, background, and inactive states. You can watch for these in your App
struct itself, or in any SwiftUI view.
First, add a property to track the key:
@Environment(\.scenePhase) var scenePhase
And now either add any logic you want to your body, or use onChange()
to observe changes directly.
As an example, we could write a view that monitors scenePhase
and prints out some text into Xcode’s debug console whenever the phase changes:
struct ContentView: View {
@Environment(\.scenePhase) var scenePhase
var body: some View {
Text("Example Text")
.onChange(of: scenePhase) { newPhase in
if newPhase == .inactive {
print("Inactive")
} else if newPhase == .active {
print("Active")
} else if newPhase == .background {
print("Background")
}
}
}
}
Download this as an Xcode project
As you can see, there are three states:
SPONSORED From March 20th to 26th, you can join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.