How to open and dismiss windows in visionOS
### Window Groups
Everything starts in the SwiftUI App file. When the app launches, a new window will be created using this window group and the `ContentView`.
import SwiftUI
@main
struct Garden01App: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
Let’s add another window group, this time with an id value.
import SwiftUI
@main
struct Garden01App: App {
var body: some Scene {
WindowGroup {
ContentView()
}
WindowGroup(id: "YellowFlower") {
YellowFlowerView()
}
}
}
Now we have a second window with an id “YellowFlower” which loads a view called `YellowFlowerView`.
Note: By default, the app will open the first WindowGroup. This is based on the order the groups appear in the App file.
### Open Window
So how do we open our new window? First we retrieve `openWindow` from the environment. Then we can call this with an id to open an instance of this window: `openWindow(id: "YellowFlower")`.
struct ContentView: View {
@Environment(\.openWindow) var openWindow
@Environment(\.dismissWindow) var dismissWindow
var body: some View {
VStack(spacing: 24) {
Text("Window Garden 🌸")
.font(.extraLargeTitle2)
Text("Open and Close a window with an id value of `YellowFlower`")
HStack {
Button(action: {
openWindow(id: "YellowFlower")
}, label: {
Label("Open Window",
systemImage: "inset.filled.center.rectangle.badge.plus")
})
Button(action: {
dismissWindow(id: "YellowFlower")
}, label: {
Label("Close Window",
systemImage: "xmark.circle")
})
}
}
.padding()
}
}
### Dismiss Window
Closing a window is very similar to opening one. We can add the `dismissWindow` environment value and call it to close a window by id. We could even add the close window button to the new window.
struct ContentView: View {
@Environment(\.openWindow) var openWindow
@Environment(\.dismissWindow) var dismissWindow
var body: some View {
VStack(spacing: 24) {
Text("Window Garden 🌸")
.font(.extraLargeTitle2)
Text("Open and Close a window with an id value of `YellowFlower`")
HStack {
Button(action: {
openWindow(id: "YellowFlower")
}, label: {
Label("Open Window",
systemImage: "inset.filled.center.rectangle.badge.plus")
})
Button(action: {
dismissWindow(id: "YellowFlower")
}, label: {
Label("Close Window",
systemImage: "xmark.circle")
})
}
}
.padding()
}
}
#### Demo 01 – Opening and closing the window
#### Demo 02 – Closing multiple windows with the same id value
You should be aware of some important details here. We can tap the open window button as many times as we like, opening multiple instances of the new window. But when we tap the close window button, all windows with an id that matches our value will be closed at the same time.
Sample code is available in Garden01 in Step Into Example Projects
_Download the Xcode project_ _with this and many more examples from Step Into**Vision**._
_Some examples are provided as standalone Xcode projects. You can find thosehere._