首页 > 解决方案 > 在 SwiftUI 中删除/替换/添加菜单

问题描述

我有一个带有 AppDelegate 的简单 SwfitUI(XCode 12.4、MacOS 11.1)Mac 应用程序。

如何删除默认的文件/编辑/查看/窗口/帮助菜单并用自定义菜单替换它们?

class AppDelegate: NSObject, NSApplicationDelegate {
    func applicationDidFinishLaunching(_ notification: Notification) {
        let _ = NSApplication.shared.windows.map { $0.tabbingMode = .disallowed }
        let mainWindow = NSApplication.shared.windows.first!
        
        mainWindow.backgroundColor = NSColor(red: 1, green: 1, blue: 1, alpha: 0.3)
        mainWindow.titlebarAppearsTransparent = true
        mainWindow.titleVisibility = .hidden        
        mainWindow.backgroundColor = NSColor(red: 1, green: 1, blue: 1, alpha: 1)
    }
    
    func applicationWillFinishLaunching(_ notification: Notification) {
        NSWindow.allowsAutomaticWindowTabbing = false
    }
}

@main
struct VeyBoardApp: App {
    @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

标签: swiftmacosswiftui

解决方案


可以这样做:

@main
struct VeyBoardApp: App {
    @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .commands {
            CommandGroup(replacing: CommandGroupPlacement.newItem) {}
            CommandGroup(replacing: CommandGroupPlacement.sidebar) {
                Button("New menu item in View") {
                    print("clicked")
                }
            }
        }
    }
}


推荐阅读