Search code examples
swiftmacosswiftui

Restoring macOS window size after close using SwiftUI WindowsGroup


By default, on a macOS app using SwiftUI the window size is not restored after the window is closed.

Is there a way to keep whatever size & position the user gave before closing the app. Essentially I'd like close & open to behave in the same way to when the user quits & opens the app?

enter image description here

Is there something that should be added here?

import SwiftUI

@main
struct testApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

Solution

  • I find out a way to work around this case by instead of closing this window we will show/hide it.

    Here is how I did in my app

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

    enter image description here