Keyboard Shortcut

You can add keyboard shortcuts to actions simply by adding .keyboardShortcut(_:) to the button:

Button(action: {}) {
	    Text("Button")
	}.keyboardShortcut("B")

You can set nearly every character as KeyEquivalent . But note, that you can’t toggle the button by simply pressing “B”. When using letters like “V”, you need to press “⌘⇧V”, when using numbers like “6”, you need to press “⌘6”. You can also specify your own modifier keys, by passing them to the modifier parameter.

.keyboardShortcut("B", modifiers: .control)

You can define a single one, or even multiple.

.keyboardShortcut("B", modifiers: [.command, .shift, .control])

A list of all event modifiers is on Apple’s developer website.

You cannot only set letters and numbers as shortcuts, but also other buttons like space or page up, accessing the KeyEquivalent properties.

.keyboardShortcut(.downArrow)

A list of all equivalents is on the Apple Developer website. You can also toggle buttons by pressing the escape button or the enter button with:

.keyboardShortcut(.cancelAction)

or

.keyboardShortcut(.defaultAction)

#swiftui #development #macos #programming #ui

SwiftUI keyboard shortcuts and menu bar.
25.50 GEEK