Skip to content

jordanbaird/SwiftKeys

Repository files navigation



Global macOS key commands

Continuous Integration Release Swift Versions Docs License

Install

Add the following dependency to your Package.swift file:

.package(url: "https://github.com/jordanbaird/SwiftKeys", from: "0.2.0")

Usage

Read the full documentation here

Creating and Observing

Start by creating an instance of KeyCommand. Observe it, and perform actions on keyDown, keyUp, and doubleTap(_:):

let command = KeyCommand(name: "ToggleMainWindow")

command.observe(.keyDown) {
    myCustomKeyDownAction()
}

command.observe(.keyUp) {
    myCustomKeyUpAction()
}

command.observe(.doubleTap(0.2)) {
    myCustomDoubleTapAction()
}

doubleTap(_:) allows you to specify a maximum time interval that the two key presses must fall within to be considered a "double-tap".

Adding a Key Recorder

Use the key command's name to create a key recorder. Then, add it to a view (note the use of KeyRecorderView for SwiftUI and KeyRecorder for Cocoa):

SwiftUI

struct SettingsView: View {
    var body: some View {
        KeyRecorderView(name: "ToggleMainWindow")
    }
}

Cocoa

class SettingsViewController: NSViewController {
    let recorder = KeyRecorder(name: "ToggleMainWindow")

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(recorder)
    }
}

The result should look something like this:

Light mode Dark mode

The recorder and command will stay synchronized with each other, so when the user records a new key combination, the command will be updated to match the new value.


For improved type safety, you can create hard-coded command names that can be referenced across your app.

Misc.swift

extension KeyCommand.Name {
    static let toggleMainWindow = Self("ToggleMainWindow")
}

AppDelegate.swift

let command = KeyCommand(name: .toggleMainWindow)

SettingsView.swift

let recorder = KeyRecorder(name: .toggleMainWindow)

Key commands are automatically stored in the UserDefaults system, using their names as keys. It's common for UserDefaults keys to be prefixed, or namespaced, according to their corresponding app or subsystem. To that end, SwiftKeys lets you provide custom prefixes that can be applied to individual names.

extension KeyCommand.Name.Prefix {
    static let settings = Self("Settings")
    static let app = Self("MyGreatApp")
}

extension KeyCommand.Name {
    // "SettingsOpen" will be the full UserDefaults key.
    static let openSettings = Self("Open", prefix: .settings)
    
    // "MyGreatApp_Quit" will be the full UserDefaults key.
    static let quitApp = Self("Quit", prefix: .app, separator: "_")
}

License

SwiftKeys is available under the MIT license.