Yet with AppKit apps, the open and save panel are typically displayed as a sheet attached to the corresponding window. This can be done with SwiftUI, I'll demo two solutions.
Ventura and Xcode 15.2. Published: June 9th 2025
The simplest solution is to grab the currently focused window using
and call panel.
passing in the result.
This is not what I'd describe as a concrete solution as it's possible that the focused window isn't the one calling the code. If that's the case then you'll want to use the solution below.
This solution is more complicated, but it should ensure that the window we pass to the panel.
function is the one from the calling method, and not just the one with focus.
We do this by using a NSViewRepresentable
and overriding the viewDidMoveToWindow instance function of that NSView, to grab an instance of the window and store it in a SwiftUI property (so it can be used with SwiftUI code).
First create a new Swift file in Xcode, and name it "NSWindowGrabber". Then copy the code from below and paste it into the new file.
With the supporting file in place, we can now add our view to the SwiftUI view and utilize it to grab a reference to the Window. First lets create a local property to store the window. In the opening lines of the view struct, add the following.
Add the WindowGrabber as a modifier to one of the views.
Now that we have our property, and the property is being populated with the window of the view, we can use it when displaying an open or save panel.
As you can see I've chosen to handle the Window being NIL, in all sense we shouldn't have to as it should only be nil when the view is being removed from display. But it never hurts to handle things like this, just in case.
Site managed by Strawberry Software's Lifeboat - running on DigitalOcean's platform.
Pages
Products Contact Weblog SwiftUI PromosCompany
About Us Environment Privacy Terms Update PlansConnect
Bluesky Facebook Threads X / Twitter Mailing List