【问题标题】:Close SwiftUI application when last window is closed [duplicate]关闭最后一个窗口时关闭 SwiftUI 应用程序 [重复]
【发布时间】:2021-04-20 22:14:25
【问题描述】:

是否可以在用户关闭最后一个窗口时关闭 macOS SwiftUI 应用程序,类似于applicationShouldTerminateAfterLastWindowClosed AppDelegate 函数。

func applicationShouldTerminateAfterLastWindowClosed(NSApplication) -> Bool

【问题讨论】:

    标签: swiftui appdelegate


    【解决方案1】:

    我在这里找到了答案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)
        
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-02
      • 1970-01-01
      相关资源
      最近更新 更多