1

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?

fbrereto
  • 35,429
  • 19
  • 126
  • 178

1 Answers1

3

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)")
    }
}
Bill
  • 469
  • 2
  • 4
  • I haven't been able to get this approach to work. If I add something to the input and try that the key commands work great, so I think this approach is fundamentally flawed. – KellyHuberty Dec 08 '19 at 19:58