iOS Swift蓝牙键盘按键检测

时间:2015-08-28 15:12:42

标签: ios swift keyboard

在iOS 8.4的Swift 2中,如何检测何时按下蓝牙键盘的UpDownSpace条形键,以便我可以采取措施进行响应? 示例代码会有所帮助。

2 个答案:

答案 0 :(得分:8)

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

您需要使用的是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。

答案 1 :(得分:0)

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