What's New

SwiftKeys 0.1.6

2022-12-02T09:43:55Z

Full Changelog: 0.1.5...0.1.6



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.1.6")

Usage

Read the full documentation here

Start by creating an instance of KeyCommand.

Observe it and perform actions on keyDown, keyUp, or both:

let command = KeyCommand(name: "ToggleMainWindow")

command.observe(.keyDown) {
    if mainWindow.isVisible {
        mainWindow.orderOut(command)
    } else {
        mainWindow.makeKeyAndOrderFront(command)
    }
}

command.observe(.keyUp) {
    if Int.random(in: 0..<10) == 7 {
        performJumpScare()
    }
}

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. See the LICENSE file for more info.

Description

  • Swift Tools 5.7.0
View More Packages from this Author

Dependencies

  • None
Last updated: Tue Dec 06 2022 11:24:31 GMT-0500 (GMT-05:00)