【问题标题】:SwiftUI: Changing default Command Menus on macOSSwiftUI:更改 macOS 上的默认命令菜单
【发布时间】:2021-01-03 17:05:58
【问题描述】:

我正在尝试更改 macOS SwiftUI 应用程序中的默认命令。我想在“查看”菜单中添加一些自定义命令,但无法正常工作。

这是我尝试过的:

@main
struct MyApp: App {

    var body: some Scene {
        
        WindowGroup {
            AppView()
                .environmentObject(AppModel.shared)
                .environment(\.managedObjectContext, AppModel.shared.cloudKitCoordinator.coreDataStack.viewContext)
        }
        .commands {
            ViewCommands()
            SidebarCommands()
            ElementCommands()
            NavigationCommands()
        }
        
    }
    
}

struct ViewCommands: Commands {

    var body: some Commands {
        
        CommandMenu("View") {
            Button("Do something View related") {}
        }
        
    }
    
}

但不是将命令附加到“查看”菜单,而是创建了第二个同名菜单:

有没有人幸运地更改了默认命令菜单,或者这只是 SwiftUI 的一部分,仍然有点原始?

【问题讨论】:

    标签: swift macos swiftui


    【解决方案1】:

    使用 CommandGroup,它具有附加或替换现有菜单的初始化选项:

    .commands {
        CommandGroup(before: CommandGroupPlacement.newItem) {
            Button("before item") {
                print("before item")
            }
        }
    
        CommandGroup(replacing: CommandGroupPlacement.appInfo) {
            Button("Custom app info") {
                // show custom app info
            }
        }
    
        CommandGroup(after: CommandGroupPlacement.newItem) {
            Button("after item") {
                print("after item")
            }
        }
    }
    

    不错的教程:https://swiftwithmajid.com/2020/11/24/commands-in-swiftui/

    【讨论】:

      【解决方案2】:

      接受的答案在建议 CommandGroup 而不是 CommandMenu 方面通常是正确的,并且有助于将我们指向 Swift with Majid(一个很棒的网站),但令人恼火的是,它并没有给我们确切的 答案 - 查看菜单是哪个CommandGroupPlacement

      为了节省所有其他人的反复试验

      CommandGroup(before: CommandGroupPlacement.toolbar) {
          Toggle("Show X", isOn: $model.settings.showX)
          Toggle("Show Y", isOn: $model.settings.showY)
          Divider()
      }
      

      【讨论】:

        【解决方案3】:

        我发现 swiftUI 删除默认菜单项的唯一方法是执行以下类:

        class TheApp{
            static func removeUnnecessaryMenus() {
                if let menu = NSApplication.shared.mainMenu {
                    menu.items.removeFirst{ $0.title == "Edit" }
                    menu.items.removeFirst{ $0.title == "File" }
                    menu.items.removeFirst{ $0.title == "Window" }
                    menu.items.removeFirst{ $0.title == "View" }
                }
            }
        }
        

        并在某些 View init() 函数上调用 TheApp.removeUnnecessaryMenus()

        这是 BAD SOLUTION ,但我找不到 SwiftUI 2 的替代方案

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-10-11
          • 2021-09-27
          • 2021-04-11
          • 2020-10-19
          • 1970-01-01
          • 2016-04-08
          • 2021-11-26
          • 1970-01-01
          相关资源
          最近更新 更多