简体   繁体   English

iOS:如何检测外部键盘上的修改键状态变化?

[英]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. 我的应用程序具有可选的用户体验,可让用户按住外部键盘上的修饰键(Shift,Option,Command)以引发某些特定行为。 (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. UIKeyCommand需要输入字符串,并在按下组合键时触发一次。 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? 是否存在iOS API,可让我跟踪外部键盘上的修改键的状态?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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