How it works
A KeyboardShortcut pairs a key with an optional set of modifier keys to give a control a keyboard equivalent, so people can trigger it without reaching for the pointer. SwiftUI activates the associated control whenever the shortcut's key combination is pressed, routing the event to the control the way a click or tap would. Reach for it on any pressable control — most often a Button or a command — to make frequent actions fast, discoverable, and consistent with platform conventions. Rather than constructing the value directly, you usually apply it through the keyboardShortcut(_:modifiers:) view modifier, which builds the KeyboardShortcut for you.
Attach a shortcut with keyboardShortcut(_:modifiers:)
The keyboardShortcut(_:modifiers:) modifier binds a key combination to the control it's applied to. You give it a KeyEquivalent and the modifier flags that must be held. Here
.keyboardShortcut("i", modifiers: .command)on theIncrementbutton means pressing Command-I runs the button's action and bumpscount.Choose the triggering key with KeyEquivalent
The first argument is a KeyEquivalent, which a single-character string literal like
"i"converts into automatically. It identifies the physical key — letters, digits, or named keys such as.return,.escape, and the arrow keys — independent of which modifiers accompany it.Require modifier keys with EventModifiers
The modifiers parameter takes an EventModifiers option set describing the keys that must be down, such as
.command,.shift,.option, or.control. Passing.commandrequires Command to be held alongside the key; the parameter defaults to.command, and you can combine flags as an array to demand several at once.Use a semantic shortcut for the primary action
Instead of naming a key, you can apply one of KeyboardShortcut's predefined values for a control's role.
.keyboardShortcut(.defaultAction)on theResetbutton marks it as the view's default action, which the system maps to Return, so the shortcut adapts to the platform rather than hard-coding a key. The companion.cancelActioncovers the Escape/cancel role.
.keyboardShortcut("i", modifiers: .command) to .keyboardShortcut("i", modifiers: [.command, .shift]) and watch the Increment button respond only to Command-Shift-I instead of Command-I.Example & preview
Press Run live & edit to compile it in your browser — then edit the Swift on the left and the preview re-renders live.
struct KeyboardShortcutDemo: View {
@State private var count = 0
var body: some View {
VStack(spacing: 16) {
Text("Count: \(count)")
.font(.title2)
Button("Increment") {
count += 1
}
.keyboardShortcut("i", modifiers: .command)
Button("Reset") {
count = 0
}
.keyboardShortcut(.defaultAction)
}
.padding()
}
}