使用 SwiftUI WindowsGroup 关闭后恢复 macOS 窗口大小

MMV*_*MMV 7 macos swift swiftui

默认情况下,在使用 SwiftUI 的 macOS 应用程序上,窗口关闭后不会恢复窗口大小。

有没有办法在关闭应用程序之前保留用户给出的任何大小和位置。本质上我希望关闭和打开的行为与用户退出和打开应用程序时的行为相同?

在此输入图像描述

这里有什么需要补充的吗?

import SwiftUI

@main
struct testApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*k G 5

我找到了一种解决这种情况的方法,我们将显示/隐藏它,而不是关闭此窗口。

这是我在我的应用程序中的做法

@main
struct PulltodoApp: App {
    @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
}

class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {

    func applicationDidFinishLaunching(_ notification: Notification) {
        let mainWindow = NSApp.windows[0]
        mainWindow?.delegate = self
    }
    func windowShouldClose(_ sender: NSWindow) -> Bool {
        NSApp.hide(nil)
        return false
    }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述