Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close SwiftUI application when last window is closed [duplicate]

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
like image 812
Duncan Groenewald Avatar asked Dec 17 '22 11:12

Duncan Groenewald


1 Answers

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)
    
        }
    }
}
like image 120
Duncan Groenewald Avatar answered May 16 '23 07:05

Duncan Groenewald