WWDC23 SALE: Save 50% on all my Swift books and bundles! >>

How to open a new window

Paul Hudson    @twostraws   

Updated for Xcode 14.2

SwiftUI provides an openWindow environment key that allows us to create new windows on macOS whenever we need them.

To get started, first edit your App scene to include a new Window. This means providing a window title, but also an identifier – a name we’ll use when asking the system to open this window:

Window("What's New", id: "whats-new") {
    Text("New in this version…")
}

That can be the only scene in your app body, or it can live alongside other windows or window groups. If it is the only window in your app, macOS will automatically remove the File > New menu item, and your app will automatically terminate when the last window is closed.

Tip: If you add an explicit navigationTitle() to your window contents, that will override any window title string.

When you want to open that window, call the openWindow environment key with the same ID value, like this:

struct ContentView: View {
    @Environment(\.openWindow) var openWindow

    var body: some View {
        Button("Show What's New") {
            openWindow(id: "whats-new")
        }
    }
}

The window can also be opened by going to the Window menu – macOS will automatically show it there, using the window title you provided.

Save 50% in my WWDC23 sale.

SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 5.0/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.