How do I create a utility window in visionOS

Asked on 08/01/2024

1 search

To create a utility window in visionOS, you can follow these steps as outlined in the session "Work with windows in SwiftUI":

  1. Define a Window Group: Start by adding a new window group that will contain the content for your utility window. You can give this window group an identifier to manage it easily.

  2. Open the Window: Use the openWindow action to open the window. This action can be called from anywhere in the SwiftUI hierarchy.

  3. Customize the Window Placement: Use the defaultWindowPlacement modifier to set the initial position and size of the window. For a utility window, you can use the utilityPanel position, which places the window close by and generally within direct touch range.

Here is a brief example based on the provided context:

struct ContentView: View {
    @Environment(\.openWindow) private var openWindow

    var body: some View {
        Button("Open Utility Window") {
            openWindow(id: "utilityWindow")
        }
    }
}

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .windowGroup(id: "utilityWindow") {
            UtilityWindowView()
        }
        .defaultWindowPlacement(.utilityPanel)
    }
}

For more detailed information, you can refer to the session Work with windows in SwiftUI at the timestamp 07:27.