Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI: Changing default Command Menus on macOS

I'm trying to change the default commands in a macOS SwiftUI app. I would like to append some custom commands to the 'View' menu, but I can't get it to work.

This is what I tried:

@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") {}
        }
        
    }
    
}

But instead of appending the command to the 'View' menu, it creates a second menu with the same name:

enter image description here

Has anyone had luck changing the default command menu's or is this just a part of SwiftUI that's still a little raw?

like image 735
Blasmo Avatar asked Jan 03 '21 17:01

Blasmo


1 Answers

Use CommandGroup, which has init options to append or replace existing menus:

.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")
        }
    }
}

Nice tutorial: https://swiftwithmajid.com/2020/11/24/commands-in-swiftui/

like image 192
Adam Avatar answered Oct 05 '22 20:10

Adam