ปิดแอปพลิเคชัน 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 App ของคุณ

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