macosswiftuimenubar

Remove Close (CMD+W) Menu Bar Button Not Working SwiftUI


My problem is simple, i'm trying to remove this button

enter image description here

found in the File section in the menu bar.

Here is what I've tried:

WindowGroup("test") {
    ContentView()
}.commands {
    CommandGroup(replacing: .saveItem) {}
}

For some reason this works in a fresh project as well. Here are some other CommandGroups that I am editing for other parts of the app

SidebarCommands()

CommandMenu("Launch") {
     ...
}

CommandGroup(replacing: .newItem) { }

CommandGroup(replacing: .toolbar) { }
        
CommandGroup(replacing: .appInfo) {
    Button("About app") {
       openWindow(id: "about")
    }
}

CommandGroup(replacing: .appTermination) {
      ...
}

CommandGroup(after: .appSettings) {
            Section {
                CheckForUpdatesView(updater: updaterController.updater)
                    .environmentObject(networkMonitor)
            }
        }

CommandGroup(after: .newItem) {
            Button("Add Item") {
                showAddItem = true
            }
        }

If this code even helps, I change the About section of my app to a custom one:

Window("About", id: "about") {
            AboutView()
                .background {
                    if aboutWindow == nil {
                        Color.clear.onReceive(NotificationCenter.default.publisher(for:
                                                                                    NSWindow.didBecomeKeyNotification)) { notification in
                            if let aboutWindow = notification.object as? NSWindow {
                                if aboutWindow.title == "About" {
                                    aboutWindow.standardWindowButton(.zoomButton)?.isHidden = true
                                }
                            }
                        }
                    }
                }.frame(width: 400, height: 250)
        }.windowResizability(.contentSize).windowStyle(.hiddenTitleBar)

I've done my research and cannot find any solutions to this problem.

Note: I saw every single post that says to do exactly what I tried, none of them worked, so i'm just creating one here.


Solution

  • The issue here is that you have multiple windows. On each window, you have to say to remove the CommandGroup saveItem, here is a example.

    WindowGroup() {
        ContentView()
    }.commands {
        CommandGroup(replacing: .saveItem) {}
    }
    
    WindowGroup("Inspector") {
        InspectorView()
    }
    

    This code won't work, because the Inspector window group does not have the command group being removed, so to fix it, you would do this:

    WindowGroup("Inspector") {
        InspectorView()
    }.commands {
        CommandGroup(replacing: .saveItem) {}
    }
    

    So in your case add

    .commands {
        CommandGroup(replacing: .saveItem) {}
    }
    

    to your About window.