Skip to content

Keyboard Shortcuts (SwiftUI)

A SwiftUI guide for coding agents. Also covers keyboardshortcut modifier, hotkey button ios, key equivalent, command key shortcut mac, ipad hardware keyboard.

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.

Use this guidance in your coding agent

Install the Better Design MCP once. Your agent then loads this page with one call.

get-swiftui-guide({ topic: "swiftui-keyboard-shortcuts" })
claude mcp add --scope user better-design --transport http https://better-design.com/api/mcp --header "Authorization: Bearer <YOUR_API_KEY>"
Browse related design systems