case active
case inactive
case background
Availability 有効性
Technology
enum ScenePhase
The system moves your app’s Scene
instances through phases that reflect a scene’s operational state. You can trigger actions when the phase changes. Read the current phase by observing the scene
value in the Environment
:
private var scenePhase (\.scenePhase)
How you interpret the value depends on where it’s read from. If you read the phase from inside a View
instance, you obtain a value that reflects the phase of the scene that contains the view. The following example uses the on
method to enable a timer whenever the enclosing scene enters the Scene
phase and disable the timer when entering any other phase:
struct MyView: View {
var model: DataModel
private var scenePhase (\.scenePhase)
var body: some View {
TimerView()
.onChange(of: scenePhase) { phase in
model.isTimerRunning = (phase == .active)
}
}
}
If you read the phase from within an App
instance, you obtain an aggregate value that reflects the phases of all the scenes in your app. The app reports a value of Scene
if any scene is active, or a value of Scene
when no scenes are active. This includes multiple scene instances created from a single scene declaration; for example, from a Window
. When an app enters the Scene
phase, expect the app to terminate soon after. You can use that opportunity to free any resources:
@main
struct MyApp: App {
private var scenePhase (\.scenePhase)
var body: some Scene {
WindowGroup {
MyRootView()
}
.onChange(of: scenePhase) { phase in
if phase == .background {
// Perform cleanup when all scenes within
// MyApp go to the background.
}
}
}
}
If you read the phase from within a custom Scene
instance, the value similarly reflects an aggregation of all the scenes that make up the custom scene:
struct MyScene: Scene {
private var scenePhase (\.scenePhase)
var body: some Scene {
WindowGroup {
MyRootView()
}
.onChange(of: scenePhase) { phase in
if phase == .background {
// Perform cleanup when all scenes within
// MyScene go to the background.
}
}
}
}
case active
case inactive
case background
static func == (ScenePhase , ScenePhase ) -> Bool
static func != (Self, Self) -> Bool
static func < (ScenePhase , ScenePhase ) -> Bool
static func <= (Self, Self) -> Bool
static func > (Self, Self) -> Bool
static func >= (Self, Self) -> Bool
var hashValue : Int
func hash(into: inout Hasher)
protocol Scene
struct SceneBuilder