Hi all,
I want to create an application with SwiftUI that either
- Quits when the last window is closed, or
- Allows one window only. That is, the New Window command is greyed out when a window is already open. I don't hold much hope for this one, not in pure swiftUI, because the commands builder doesn't allow logic.
I am pretty sure this used to be a simple configuration on the Mac, this would be my best hope.
The first point can easily be solved through the use of a custom class conforming to the NSApplicationDelegate
, implemented like this:
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
return true
}
}
and then adding this to the main app file:
@NSApplicationDelegateAdaptor private var appDelegate: AppDelegate
On your second point, if needed, you can use the new in Ventura Window
struct as the main scene of your app, like this:
@main struct SingleWindowApp: App {
var body: some Scene {
Window("SingleWindow", id: "main") {
ContentView()
}
}
}