Restoring macOS window after close – SwiftUI WindowsGroup

Typical behavior for macOS apps is that the apps will preserve their size and position when closed (Command + W) or quit (Command + Q) by the user. 

11sgE

 

When using SwiftUI & WindowsGroup that’s not the case though: although it works as designed when quitting, it forgets position and size when closing the window (Command + W).

I’m hoping this gets addressed in the future, but until then I’m using AppDelegate to intercept the close command and instead hiding the window. 

@main

struct MarsManagedApp: 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

    }

}

Works like a charm, thanks to Mark G for the tip. 

Feedback / suggestions? Reach me at mastodon.social/@MarcMasVi or @MarcMasVi

Marc