You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在macOS SwiftUI应用中选择性移除默认菜单栏菜单(File、Edit、View)

选择性移除macOS SwiftUI应用的默认菜单

在SwiftUI中,你可以通过自定义Commands精准控制保留或移除指定默认菜单,无需使用会清空所有菜单的.commandsRemoved()。以下是两种纯SwiftUI实现方案:

方案一:完全自定义菜单栏,仅保留所需系统菜单

直接创建自定义Commands结构体,只包含你需要保留的系统菜单(如AppName菜单)和自定义命令:

@main
struct YourToolApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .commands {
            // 保留AppName菜单(包含About、Quit等系统默认项)
            CommandGroup(replacing: .appInfo) {
                Button("About YourTool") {
                    NSApp.orderFrontStandardAboutPanel(nil)
                }
                Divider()
                Button("Quit YourTool") {
                    NSApp.terminate(nil)
                }
            }
            
            // 添加工具专属的自定义命令
            CommandGroup(after: .appInfo) {
                Button("Run Tool Action") {
                    // 执行工具核心逻辑
                }
            }
            
            // 不添加File、Edit、View对应的CommandGroup,对应菜单会自动隐藏
        }
    }
}

方案二:精准移除指定默认菜单组

如果想保留部分系统菜单,仅移除File、Edit、View这类无关菜单,可以用CommandGroup(replacing:)将对应菜单组替换为空内容:

@main
struct YourToolApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .commands {
            // 移除File菜单
            CommandGroup(replacing: .file) {}
            // 移除Edit菜单
            CommandGroup(replacing: .edit) {}
            // 移除View菜单
            CommandGroup(replacing: .view) {}
            
            // 保留其他默认菜单(如Window、AppName),也可添加自定义命令
            CommandGroup(after: .window) {
                Button("Reset Tool State") {
                    // 重置工具状态逻辑
                }
            }
        }
    }
}

注意事项

  • macOS 13及以上版本,CommandGroup的replacing参数支持直接指定系统内置组(.file、.edit、.view等),替换为空闭包即可隐藏对应菜单。
  • 若无需自定义AppName菜单的默认项(About、Services、Quit等),无需额外替换.appInfo,系统会自动保留该菜单。
  • 该方案完全基于SwiftUI原生Commands系统,无需依赖AppKit的NSMenu操作,符合SwiftUI惯用写法。

内容的提问来源于stack exchange,提问作者Tzar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 03:32:49