Is it possible to close a macOS SwiftUI application when the last window is closed by the user, similar to the applicationShouldTerminateAfterLastWindowClosed
AppDelegate function.
func applicationShouldTerminateAfterLastWindowClosed(NSApplication) -> Bool
I found the answer here https://www.hackingwithswift.com/quick-start/swiftui/how-to-add-an-appdelegate-to-a-swiftui-app
Create a class for the AppDelegate
import Foundation
import AppKit
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
return true
}
}
Add a property wrapper to your SwiftUI App class
import SwiftUI
@main
struct SwiftUIApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
.frame(minWidth: 300, idealWidth: 300, maxWidth: .infinity, minHeight: 300, idealHeight: 300, maxHeight: .infinity)
}
}
}
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