Handling a single window app on MacOS with Swift

Hi all,

I want to create an application with SwiftUI that either

  1. Quits when the last window is closed, or
  2. 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.

Answered by BabyJ in 720561022

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()
        }
    }
}
Accepted Answer

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()
        }
    }
}

Thanks! The first one works. I can't use the latest SwiftUi but that looks useful for the future.

Handling a single window app on MacOS with Swift
 
 
Q