Search code examples
macosswiftuiswiftui-windowgroup

How to limit the number of windows in a WindowGroup?


I am building a single window application and want to use the new SwiftUI App Lifecycle.

import SwiftUI

@main
struct SingleWindowApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

The default implementation of WindowGroup allows multiple instances of the window (i.e. if you hit ⌘N). I wasn’t able to find a modifier that changes that behaviour.

How would I limit the number of windows within a WindowGroup to just 1?


Solution

  • This should do it:

    import SwiftUI
    
    @main
    struct SingleWindowApp: App {
        var body: some Scene {
            WindowGroup {
                ContentView()
            }
            .commands {
                CommandGroup(replacing: .newItem, addition: { })
            }
        }
    }