Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open another window in SwiftUI, macOS?

Tags:

macos

swiftui

I'd like to show a second window with different content in a SwiftUI app on macOS. I can't find any documentation on this. The attempt below doesn't work. Does anyone know how to do it?

class AppState: ObservableObject {
    @Published var showSecondWindow: Bool = false
}

@main
struct MultipleWindowsApp: App {
    @StateObject var appState = AppState()
    var body: some Scene {
        WindowGroup {
            ContentView().environmentObject(appState)
        }
        WindowGroup {
            if appState.showSecondWindow {
                SecondContent()
            }
        }
    }
}

struct ContentView: View {
    @EnvironmentObject var appState: AppState
    var body: some View {
        VStack {
            Text("Hello, world!")
            Button("Open 2nd Window") {
                appState.showSecondWindow = true
            }
        }.padding()
    }
}

struct SecondContent: View {
    var body: some View {
        Text("Hello, from window #2.")
    }
}
like image 492
Rob N Avatar asked Nov 13 '20 15:11

Rob N


1 Answers

Here's an extension for creating a window for NSViewController, assigning a title and opening it.

extension View {
    
    @discardableResult
    func openInWindow(title: String, sender: Any?) -> NSWindow {
        let controller = NSHostingController(rootView: self)
        let win = NSWindow(contentViewController: controller)
        win.contentViewController = controller
        win.title = title
        win.makeKeyAndOrderFront(sender)
        return win
    }
}

Usage:

Button("Open 2nd Window") {
    SecondContent().openInWindow(title: "Win View", sender: self)
}

To close the window

NSApplication.shared.keyWindow?.close()
like image 167
bauerMusic Avatar answered Oct 13 '22 22:10

bauerMusic