How to open and dismiss volumes in visionOS

Opening and dismissing Volumes in visionOS is very similar to opening and dismissing Windows.

In fact, Volumes are Windows, presented in a different style. We can use the scene modifier windowStyle set to .volumetric. to create a volume.

struct Garden07App: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        // Add this line to present a window as a volume
        .windowStyle(.volumetric)
    }
}

Open a volume by default

Note: By default, most Xcode templates are configured to present a Window as the primary scene type. You can change this: project configuration file > Info > Application Scene Manifest > Preferred Default Scene Session Role

Now when our project launches, a volume will be opened with ContentView as the SwiftUI root.

Open a volume

We can open a volume using the same concept as opening a window.

struct ContentView: View {
    // 1. Import the openWindow environment variable
    @Environment(\.openWindow) var openWindow

    var body: some View {
        RealityView { content, attachments in
        ...
        } update: { content, attachments in
        ...
        } attachments: {
            Attachment(id: "🌸") {
                Flower2D(flowerEmoji: "🌸")
                    .onTapGesture {
                        // 2. Call openWindow with the id of the volume we want to open
                        openWindow(id: "🌸")
                    }
            }
        }
    }
}

Dismiss a volume

We can dismiss a volume in code the same way as we open one.

struct Flower01Scene: View {
    // 1. Import the dismissWindow environment variable
    @Environment(\.dismissWindow) var dismissWindow

    var body: some View {
        Flower2D(flowerEmoji: "🌸")
            .onTapGesture {
                // 2. Call dismissWindow with the id of the volume we want to close
                dismissWindow(id: "🌸")
            }
    }
}

Demo: Tap the flower in the main volume to open a new volume. Tap the flower in the new volume to dismiss that volume.

visionOS simulator video showing a window open several small volumes

Sample code is available in Garden07 in the Step Into Example Projects repo.

Support our work so we can continue to bring you new examples and articles.

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 those here.

Questions or feedback?