The keyboardShortcut modifier attaches a shortcut to any view. Pressing it is equivalent to
directly triggering the view's primary action: a button fires, a toggle flips. iOS 14 and
macOS 11 and up.
Defining a Shortcut
Pass a KeyEquivalent and an optional set of modifier keys. Omit the modifiers and SwiftUI
uses Command by default.
Button("Print message") {
print("Hello World!")
}
.keyboardShortcut("p", modifiers: [.command, .shift])
KeyEquivalent is expressible by a one-character string literal and also defines named keys
such as arrows, escape, delete, and home. The modifiers are EventModifiers, an option set
covering shift, command, control, and option.
Beyond Buttons
The modifier works on any interactive view, not only buttons. A shortcut on a Toggle
switches its value.
Toggle(isOn: $isEnabled) {
Text(String(isEnabled))
}
.keyboardShortcut("t")
Attached to a container such as VStack or HStack, the shortcut applies to the first
interactive child in that hierarchy.
VStack {
Button("Print message") { print("Hello World!") }
Button("Delete message") { print("Message deleted.") }
}
.keyboardShortcut("p") // triggers the first button
Gotchas
- In the simulator, keyboard shortcuts only work after pressing the Capture Keyboard button in the simulator chrome.
- On a container, only the first interactive child gets the shortcut; put the modifier on the exact view you mean to trigger.