【问题标题】:iOS Swift Bluetooth Keyboard keypress detectioniOS Swift 蓝牙键盘按键检测
【发布时间】:2015-11-23 07:23:55
【问题描述】:

在 iOS 8.4 上的 Swift 2 中,我如何检测蓝牙键盘的 UpDownSpace 条键何时被按下,以便我可以做出响应? 示例代码会很有帮助。

【问题讨论】:

    标签: ios swift keyboard


    【解决方案1】:

    对不起,我来晚了,我才意识到我可以帮助你。

    你需要使用的是 UIKeyCommand。看看这个:http://nshipster.com/uikeycommand/

    请注意,要检测箭头键按下,您需要 input: UIKeyInputLeftArrow 而不是 input: "j"(或等效项)。您还希望没有修饰符(因此用户不必按 CMD 向左箭头):请参阅 Key Commands with no modifier flags—Swift 2

    基本上,在您的 viewdidload 之后(外部)您会想要类似的东西:

    override func canBecomeFirstResponder() -> Bool {
        return true
    }
    
        override var keyCommands: [UIKeyCommand]? {
        return [
            UIKeyCommand(input: UIKeyInputDownArrow, modifierFlags: [], action: "DownArrowPress:"),
            UIKeyCommand(input: UIKeyInputUpArrow, modifierFlags: [], action: "UpArrowPress:"),
            UIKeyCommand(input: " ", modifierFlags: [], action: "SpaceKeyPress:")]
        }
    
    // ...
    
    func DownArrowPress(sender: UIKeyCommand) {
     // this happens when you press the down arrow.   
    }
    func UpArrowPress(sender: UIKeyCommand) {
     // this happens when you press the up arrow.   
    }
    func SpaceKeyPress(sender: UIKeyCommand) {
     // this happens when you press the space key.   
    }
    

    我希望这会有所帮助,如果您需要更多帮助或有什么不对劲的地方,请回复 @owlswipe。

    【讨论】:

    • 我尝试将UIKeyCommandinput: " " 一起应用,但按下空格键时不会调用该操作。它适用于其他键,例如返回键:input: "\r" (Swift 5)
    【解决方案2】:

    owlswipe 的 answer 为我工作,但是,我必须对 Swift 5 进行以下更改:

      @objc func DownArrowPress(sender: UIKeyCommand) {
        print("DOWNARROWPRESS")
      }
      @objc func UpArrowPress(sender: UIKeyCommand) {
        print("UPARROWPRESS")
      }
    
      override var keyCommands: [UIKeyCommand]? {
      return [
        UIKeyCommand(input: UIKeyCommand.inputDownArrow, modifierFlags: [], action: #selector(DownArrowPress)),
        UIKeyCommand(input: UIKeyCommand.inputUpArrow, modifierFlags: [], action: #selector(UpArrowPress))
        ]
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-07
      • 1970-01-01
      • 1970-01-01
      • 2017-05-09
      相关资源
      最近更新 更多