Add the following dependency to your Package.swift
file:
.package(url: "https://github.com/jordanbaird/SwiftKeys", from: "0.1.0")
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):
struct SettingsView: View {
var body: some View {
KeyRecorderView(name: "ToggleMainWindow")
}
}
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, as well as a global, shared prefix that will automatically apply to every name that doesn't explicitly specify otherwise.
extension KeyCommand.Name.Prefix {
public override var sharedPrefix: Self {
Self("MyApp")
}
}
In the example above, the name "ToggleMainWindow" would become "MyAppToggleMainWindow" when used as a UserDefaults
key.
SwiftKeys is licensed under the MIT license.