简体   繁体   中英

iOS: How do I detect modifier key state changes on an external keyboard?

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?

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)")
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM