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:
Has anyone had luck changing the default command menu's or is this just a part of SwiftUI that's still a little raw?
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With