如何删除 macOS SwiftUI 标题选项?

How can I remove macOS SwiftUI title options?

所以默认情况下,我在 macOS SwiftUI 中看到我的应用程序的这个选项:

我想删除文件、编辑、查看,window 并只保留帮助。我怎样才能删除它们?


我试图删除文件,编辑...我在互联网上找到了这段代码,但不确定如何使它们起作用:

  @main
struct My_TestApp: App {
    
    @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    final class AppDelegate: NSObject, NSApplicationDelegate {
        
        func applicationWillUpdate(_ notification: Notification) {
            if let menu = NSApplication.shared.mainMenu {
                menu.items.removeFirst{ [=10=].title == "File" }
                menu.items.removeFirst{ [=10=].title == "Edit" }
                menu.items.removeFirst{ [=10=].title == "View" }
                menu.items.removeFirst{ [=10=].title == "Window" }
            }
        }
        
    }

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

Xcode 错误是:

Trailing closure passed to parameter of type 'Int' that does not accept a closure

它被命名为主菜单,以防万一。

一种可能的方法是在启动后过滤创建的菜单。所以创建应用程序委托适配器并完成,执行以下操作:

func applicationDidFinishLaunching(_ notification: Notification) {
    guard let mainMenu = NSApp.mainMenu else { return }
    let newMenu = NSMenu()
    if let appMenu = mainMenu.items.first {
        mainMenu.removeItem(appMenu) // cannot be in both, so remove from previous
        newMenu.addItem(appMenu)
    }
    if let helpMenu = NSApp.mainMenu?.items.last {
        mainMenu.removeItem(helpMenu)
        newMenu.addItem(helpMenu)
    }
    NSApp.mainMenu = newMenu   // << here !!
}

测试 Xcode 13.4 / macOS 12.4

backup