Restore Window Size on MacCatalyst Apps

Sometimes its easier to just enable MacCatalyst on an iOS app to bring it to the Mac than to fiddle around with a dedicated Mac target or using the Mac version of SwiftUI. The drawback is that you don’t have access to AppKit but have to stick with UIKit / SwiftUI. So some quite useful features of AppKit are not available in MacCatalyst.

E.g. there is this nice AppKit construct to save and restore the window size and position between app launches:

But there is no equivalent in MacCatalyst since iOS apps don’t mess around with windows. In this post I’ll show how to achieve a similar behaviour in MacCatalyst.

First of all we have to implement a SceneDelegate for our app. That’s straightforward for UIKit but a little more complicated for SwiftUI. Take a look at this post for that:

It’s a good idea to remember the corresponding window scene in the delegate:

And then we’ll implement this delegate function:

After we’ve made sure that we do have a window scene we’ll store that scene in the above mentioned var. In the computed property preferredRect we’ll look for a possibly stored window rect. How that is stored we’ll see in a minute.

If that rect is available we put it in GeometryPreferences for the Mac and request an update of the geometry. That’s it for the restore.

To store the current geometry of our window we can use any View in our app with a GeometryReader:

Here we get the current system frame from our sceneDelegate and store in the UserDefaults. Well, that’s it. Not too difficult, is it?

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert