SwiftUI Keyboard Shortcuts and macOS Menu Bar.

Luca Jonscher
ITNEXT
Published in
2 min readAug 8, 2020

--

With SwiftUI 2, it’s incredibly easy to add keyboard shortcuts to actions and to add buttons to your app’s menu bar.

Keyboard Shortcut

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

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.

You can define a single one, or even multiple.

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.

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:

or

--

--

Writer for

Designer, Developer, Creative. Freelance graphic designer. From Germany. Thrice Apple Swift Student Challenge winner.