Закройте приложение SwiftUI после закрытия последнего окна [дубликат]

Jan 16 2021

Можно ли закрыть приложение MacOS SwiftUI, когда последнее окно закрывается пользователем, аналогично applicationShouldTerminateAfterLastWindowClosedфункции AppDelegate.

func applicationShouldTerminateAfterLastWindowClosed(NSApplication) -> Bool

Ответы

2 DuncanGroenewald Jan 16 2021 at 04:20

Я нашел ответ здесь https://www.hackingwithswift.com/quick-start/swiftui/how-to-add-an-appdelegate-to-a-swiftui-app

Создайте класс для AppDelegate

import Foundation
import AppKit

class AppDelegate: NSObject, NSApplicationDelegate {
    func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
        return true
    }
}

Добавьте оболочку свойств в свой класс приложения SwiftUI

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