KeyboardShortcut Not Functioning in SwiftUI

While a bit new to keyboard shortcuts, I am looking to add a specific piece of functionality to my app. Specifically, I am wanting to allow my user to be able to trigger an action by pressing the spacebar, both on iPadOS, when using a keyboard, and macOS. This would function similarly to how video editing programs like iMovie and Final Cut Pro work.

I have a "play" button in place, and am trying to add a modifier, like so;

Code Block
Button(action: {
self.isPlaying.toggle()
}) {
Image(systemName: isPlaying ? "pause.fill" : "play.fill")
}.keyboardShortcut(.space)
.help("Play timeline")


Based on the KeyboardShortcut documentation, this should be all I need to get things running. However, when building and testing my app, using the spacebar does not do anything (nor does the shortcut appear in the keyboard shortcuts list).

Replies

If you omit the modifiers argument, if defaults to .command, so if you try cmd + space, your keyboard shortcut will probably work.

Code Block swift
public func keyboardShortcut(_ key: KeyEquivalent, modifiers: EventModifiers = .command) -> some View

Try .keyboardShortcut(.space, modifiers: []) and space on its own should work.