关闭最后一个窗口时关闭 SwiftUI 应用程序 [英] Close SwiftUI application when last window is closed

查看:42
本文介绍了关闭最后一个窗口时关闭 SwiftUI 应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

我在这里找到了答案 https://www.hackingwithswift.com/quick-start/swiftui/how-to-add-an-appdelegate-to-a-swiftui-app

为 AppDelegate 创建一个类

Create a class for the AppDelegate

import Foundation
import AppKit

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

向您的 SwiftUI 应用类添加属性包装器

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

这篇关于关闭最后一个窗口时关闭 SwiftUI 应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆