Home > Enterprise >  How to display only one window in my macOS app?
How to display only one window in my macOS app?

Time:12-11

I know that there's a quick hack for this, that basically does:

var body: some Scene {

    WindowGroup
    {
        ContentView()            
    }
    .commands {
        CommandGroup(replacing: CommandGroupPlacement.newItem) {
            //New window command
            EmptyView()
        }
    }
}

but it simply removes the "New Window" menu, which I don't want to do.

My goal is let only one window to be displayed. So I'm assuming the skeleton should be this:

@Environment(\.openWindow) var openWindow

var body: some Scene {

    WindowGroup
    {
        ContentView()            
    }
    .commands {
        CommandGroup(replacing: CommandGroupPlacement.newItem) {

            Button(action: {
                //New window

                //openWindow(id: .self)
                
            }) { Text("New Window")}
                .keyboardShortcut("N", modifiers: [.command])
        }
    }
}

But how to:

  1. Display a new window.
  2. See if it is already displayed and in that case do nothing.

CodePudding user response:

The simplest way would be to use no WindowGroup at all:

@main
struct SO_mac_TestsApp: App {
        
    var body: some Scene {

        Window("My only Window", id: "myWindow") {
            ContentView()
        }
    }
}

But be aware that closing this window quits the app.

  • Related