May 02, 2024 iOS

SwiftUI 2: the way to open view in new window

In SwiftUI 2 and later, you can use the WindowGroup and Window APIs to open views in new windows. This allows you to create multi-window experiences in your SwiftUI app. Here’s how you can open a view in a new window:

First, you need to define a new WindowGroup in your App struct, and then use the Window API to open a new window containing your desired view.

Here’s an example:

import SwiftUI

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        
        // Define a new WindowGroup for the second window
        WindowGroup("SecondWindow") {
            SecondContentView()
        }
    }
}

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Main Window")
            Button("Open Second Window") {
                // Open the second window
                if let secondWindow = UIApplication.shared.windows.first(where: { $0.isKeyWindow == false }) {
                    secondWindow.isHidden = false
                }
            }
        }
    }
}

struct SecondContentView: View {
    var body: some View {
        VStack {
            Text("Second Window")
        }
    }
}

In this example:

  • We define an App struct and specify the main window’s content using WindowGroup.
  • We also define a new WindowGroup for the second window, specifying its content with SecondContentView.
  • In the ContentView, there’s a button that, when tapped, retrieves the second window (if it exists) and shows it by setting its isHidden property to false.
  • The SecondContentView is a simple view displayed in the second window.

This code demonstrates how to open a new window containing a different view in SwiftUI 2 and later. Remember that multi-window support is available only on iPad and Mac Catalyst apps running on iPadOS 13.4 or later and macOS 11.0 or later.