Skip to content

Instantly share code, notes, and snippets.

@sindresorhus
Last active August 22, 2022 02:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sindresorhus/434d1721df71664b76bc89c04acb6d21 to your computer and use it in GitHub Desktop.
Save sindresorhus/434d1721df71664b76bc89c04acb6d21 to your computer and use it in GitHub Desktop.
For a macOS app, if you want an action in both the main menu and the UI, it's quite boilerplaty. You need to synchronize some value with @focusedvalue. What if we had something like this?
struct CameraCommands: Commands {
var body: some Commands {
CommandGroup(replacing: .newItem) {
// This menu item will be enabled when the key view has a button with `.command(.takePhoto)`. The action logic is implemented in the button.
Placeholder("Take Photo", id: .takePhoto)
// Alternatively, it could be:
// Button("Take Photo") {}
// .placeholder(.takePhoto)
}
}
}
// ...
struct MainScreen: View {
var body: some View {
Button("Take Photo") {
// Logic here
}
.command(.takePhoto)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment