Apr 26, 2024 iOS

SwiftUI 2: the way to open view in new window

Certainly! In SwiftUI 2.0, you can open a new view in a separate window using the .openWindow environment key. Let’s break down the steps:

  1. Define Your App State: First, create an AppState that holds the selected book (or any other relevant data). For example:
class AppState: ObservableObject {
    @Published var selectedBook: BookViewModel?
}

Configure Your App Scene: In your main app scene, set up your WindowGroup and define additional windows. For instance:

@main
struct MySwiftUIApp: App {
    @StateObject var appState = AppState()

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(appState) // Inject app state
        }

        // Define additional windows
        Window("Book Viewer", id: "book") {
            BookView(model: appState.selectedBook)
        }
    }
}

Create Your ContentView: In your main content view (ContentView), use the .openWindow environment key to open the new window. For example:

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

    var body: some View {
        Button("Open Book") {
            openWindow(id: "book") // Open the BookView in a new window
        }
    }
}
  1. Replace "book" with any unique identifier you’d like for your window.
  2. Handle the Deep Link (Bonus): If you want to open a different view (e.g., SettingsView) from code, you can use the same approach. Define a new window and use the .openWindow environment key to trigger it.

Remember that this approach works well for macOS apps. If you need cross-platform behavior, consider using platform-specific code or AppKit for more complex scenarios 1234.