SwiftUI How to add keyboard shortcuts using keyboardShortcut()

19 min read

In SwiftUI, you can add keyboard shortcuts using the keyboardShortcut() modifier. Here's how you can do it:

  1. Add the keyboardShortcut() modifier to a view.
  2. Pass a KeyboardShortcut object to the modifier, specifying a Key and an optional modifiers parameter.

Here's an example that adds a keyboard shortcut to a button:

import SwiftUI

struct ContentView: View {
    var body: some View {
        Button("Click Me") {
            // Add button action here
        }
        .keyboardShortcut(.defaultAction) // Use default action (Return key)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

In this example, the keyboard shortcut is set to the default action, which is triggered by pressing the Return or Enter key.

You can also specify custom keyboard shortcuts by creating a KeyboardShortcut object manually. Here's an example:

struct ContentView: View {
    var body: some View {
        Text("Hello, World!")
            .keyboardShortcut(
                KeyboardShortcut(Key("a"), modifiers: .control)
            ) {
                // Add action for the custom keyboard shortcut here
            }
    }
}

In this example, the keyboard shortcut is set to Control + A. When the user presses this combination, the action closure will be executed.

You can add multiple keyboard shortcuts to a view by using multiple keyboardShortcut() modifiers chained together.

Note: Keyboard shortcuts are only available on macOS. They are not supported on iOS, iPadOS, or watchOS.