跳转至
Protocol

Scene

This protocol is used to create different content areas on the screen.

Declaration

protocol Scene

Overview

On-screen Scenes are the building blocks of any app built entirely in SwiftUI. They can look different depending on the platform the app is running on. For example, in iOS, the screen usually only displays one scene at a time. In macOS, every window in an app might be a different scene.

Scenes can either be custom, or one of the primitives like WindowGroup or DocumentGroup.

Creating a Scene

Using primitive Scenes

Primitive scenes like WindowGroup can go directly in the body of your App.

@main
struct SuperSimpleApp: App {
    var body: some Scene {
        WindowGroup {
            Text("This is an entire app! 🙌")
        }
    }
}
A white view that displays the text ""This is an entire app! 🙌""

Using custom Scenes

Just like how custom Views are made out of a var body of smaller Views, custom Scenes are made out of a var body of smaller Scenes.

@main
struct MacCompatibleApp: App {
    var body: some Scene {
        CustomScene()
    }

struct CustomScene: Scene {
    var body: some Scene {
        WindowGroup {
            Text("This is a mac-compatible app! 💻")
        }

        #if os(macOS)
        Settings {
            SettingsView()
        }
        #endif
    }
}
A white view that displays the text "This is a mac-compatible app! 💻"

Modifiers

Just like how Views have a bunch of custom modifiers that work right out of the box, Scene provides default implementations of many useful modifiers. These can be used to do things like adding macOS commands, changing the toolbar, and adding support for app storage.

Getting Scene Status

The scenePhase environment value can easily be read in a scene to respond to whether the scene is active or in another state. It returns an enumeration of type ScenePhase.

struct StateAdaptingScene: Scene {
    @Environment(\.scenePhase) private var scenePhase
    var body: some Scene {
        WindowGroup {
            Text(scenePhase == .active ? "Active!" : "Inactive")
        }
    }
}

Availability

iOS 14.0+

macOS 11.0+

tvOS 14.0+

watchOS 7.0+

Topics


Instance Property

body The entry point for building custom Scenes.


Instance Method

commands(content:) Use this modifier to add a menu and keyboard shortcuts to your macOS and iPadOS apps.

defaultAppStorage(_:) Use this modifier to change a scene's default storage for the @AppStorage property wrapper.

handlesExternalEvents(matching:) Specifies a modifier to indicate if this Scene can be used when creating a new Scene for the received External Event.

onChange(of:perform:) Use this method to watch for changes in a variable value.


Associated Type

Body The type of the body variable in a scene.