使用SwiftUI及SwiftUI生命周期的macOS应用如何移除默认菜单项?
解决方案
以下方案仅适用于macOS平台,iOS、iPadOS等平台不存在系统顶层菜单的设计。
有两种常用的方式可以移除SwiftUI macOS应用的默认系统菜单项:
方案1:使用SwiftUI原生CommandGroup替换默认菜单组(推荐)
通过CommandGroup的replacing参数指定要替换的系统默认菜单组,传入空的内容即可移除对应菜单:
var body: some Scene { WindowGroup { ContentView() } .commands { // 移除File默认菜单 CommandGroup(replacing: .fileCommands) { } // 移除Edit默认菜单 CommandGroup(replacing: .editCommands) { } // 移除View默认菜单 CommandGroup(replacing: .viewCommands) { } // 移除Window默认菜单 CommandGroup(replacing: .windowCommands) { } // 移除Help默认菜单 CommandGroup(replacing: .helpCommands) { } // 添加自定义菜单 CommandMenu("TEST") {} } }
该方案符合SwiftUI原生设计规范,不会破坏系统基础交互逻辑,优先推荐使用。
方案2:直接清空App主菜单(完全自定义场景)
如果需要彻底清空所有默认菜单,完全自定义菜单结构,可以直接修改NSApp的主菜单对象:
@main struct TestApp: App { init() { // 清空所有默认主菜单项 NSApp.mainMenu = NSMenu() } var body: some Scene { WindowGroup { ContentView() } .commands { CommandMenu("TEST") {} } } }
注意:该方案会移除所有系统预置的菜单功能,若后续需要使用复制粘贴、窗口缩放等标准系统能力,需要手动补充实现。
效果参考

内容的提问来源于stack exchange,提问作者XYZ
相关产品推荐
相关产品推荐

