How it works
OpenWindowAction is a callable action value that opens a new instance of one of your app's scenes, letting any view programmatically bring up an additional window. Rather than constructing window-management code by hand, you retrieve the action from the environment and call it like a function, identifying the scene to present. Reach for it whenever a control or event in your interface needs to spin up a separate window — an inspector, a document, or an auxiliary panel — on platforms such as macOS and iPadOS that support multiple windows.
Read the action from the environment with @Environment(\.openWindow)
SwiftUI supplies the live OpenWindowAction through the environment, so you don't initialize one yourself — you declare a property bound to the openWindow key path. Here
@Environment(\.openWindow) private var openWindowinjects the action into the view, making it available wherever the body needs it.Call the action to present a scene
OpenWindowAction conforms to a callable form, so the property behaves like a function: invoking it asks SwiftUI to open a window for the matching scene. In the example,
openWindow(id: "inspector")is the call that triggers the new window.Identify the scene with the id parameter
The id argument names which WindowGroup or Window to open, matching the identifier you assigned to that scene in your App declaration. The
id: "inspector"value routes the request to the scene registered under that string; passing a value-based overload instead opens a scene that takes presented data.Trigger the call from a control
Because the action is just a function call, you place it inside any event handler. Here it lives in the closure of
Button("Open New Window"), so each tap performsopenWindow(id: "inspector")and brings up another window.
openWindow(id: "inspector") to an id that no scene in your app declares, and notice that the call has no effect because OpenWindowAction can only open scenes it can resolve.Example & preview
Press Run live & edit to compile it in your browser — then edit the Swift on the left and the preview re-renders live.
struct OpenWindowActionDemo: View {
@Environment(\.openWindow) private var openWindow
var body: some View {
VStack(spacing: 16) {
Text("Window Opener")
.font(.headline)
Button("Open New Window") {
openWindow(id: "inspector")
}
.buttonStyle(.borderedProminent)
}
.padding()
}
}