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.")
}
}
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With