XUtils

KeyboardShortcuts

Add user-customizable global keyboard shortcuts to your macOS app. Includes a Cocoa and SwiftUI component.


Install

Add https://github.com/sindresorhus/KeyboardShortcuts in the “Swift Package Manager” tab in Xcode.

Cocoa

Using KeyboardShortcuts.RecorderCocoa instead of KeyboardShortcuts.Recorder:

import AppKit
import KeyboardShortcuts

final class SettingsViewController: NSViewController {
	override func loadView() {
		view = NSView()

		let recorder = KeyboardShortcuts.RecorderCocoa(for: .toggleUnicornMode)
		view.addSubview(recorder)
	}
}

API

See the API docs.

Tips

Default keyboard shortcuts

Setting a default keyboard shortcut can be useful if you’re migrating from a different package or just making something for yourself. However, please do not set this for a publicly distributed app. Users find it annoying when random apps steal their existing keyboard shortcuts. It’s generally better to show a welcome screen on the first app launch that lets the user set the shortcut.

import KeyboardShortcuts

extension KeyboardShortcuts.Name {
	static let toggleUnicornMode = Self("toggleUnicornMode", default: .init(.k, modifiers: [.command, .option]))
}

Get all keyboard shortcuts

To get all the keyboard shortcut Name’s, conform KeyboardShortcuts.Name to CaseIterable.

import KeyboardShortcuts

extension KeyboardShortcuts.Name {
	static let foo = Self("foo")
	static let bar = Self("bar")
}

extension KeyboardShortcuts.Name: CaseIterable {
	public static let allCases: [Self] = [
		.foo,
		.bar
	]
}

// …

print(KeyboardShortcuts.Name.allCases)

And to get all the Name’s with a set keyboard shortcut:

print(KeyboardShortcuts.Name.allCases.filter { $0.shortcut != nil })

FAQ

How is it different from HotKey?

HotKey is good for adding hard-coded keyboard shortcuts, but it doesn’t provide any UI component for the user to choose their own keyboard shortcuts.

Why is this package importing Carbon? Isn’t that deprecated?

Most of the Carbon APIs were deprecated years ago, but there are some left that Apple never shipped modern replacements for. This includes registering global keyboard shortcuts. However, you should not need to worry about this. Apple will for sure ship new APIs before deprecating the Carbon APIs used here.

Does this package cause any permission dialogs?

No.

How can I add an app-specific keyboard shortcut that is only active when the app is?

That is outside the scope of this package. You can either use NSEvent.addLocalMonitorForEvents, NSMenuItem with keyboard shortcut (it can even be hidden), or SwiftUI’s View#keyboardShortcut() modifier.


Articles

  • coming soon...