0
votes

My app has an optional user experience that lets a user hold down the modifier keys (shift, option, command) on an external keyboard to elicit some specific behaviors. (This experience would also be provided on-screen when a keyboard is not attached.)

UIKeyCommand requires an input string, and is fired once when the key combination is pressed. I want to track state changes of just the modifier keys over time, as the user presses/releases them.

Is there an iOS API that lets me track the state of modifier keys on an external keyboard?

1

1 Answers

3
votes

Have you tried using an empty string for input?

class ViewController: UIViewController {
    override var canBecomeFirstResponder: Bool {
        return true
    }

    override var keyCommands: [UIKeyCommand]? {
        return [
            UIKeyCommand(input: "", modifierFlags: [.shift], action: #selector(shiftPressed(key:))),
            UIKeyCommand(input: "", modifierFlags: [.alphaShift], action: #selector(capslockPressed(key:)))
        ]
    }

    @objc func shiftPressed(key: UIKeyCommand) {
        print("shift pressed \(key)")
    }

    @objc func capslockPressed(key: UIKeyCommand) {
        print("capslock pressed \(key)")
    }
}