Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Swift Bluetooth Keyboard keypress detection

In Swift 2 on iOS 8.4 how do I detect when a Bluetooth keyboard's Up, Down, or Space bar keys are pressed so I can respond with an action? Example code would be helpful.

like image 590
LearningGuy Avatar asked Aug 28 '15 15:08

LearningGuy


1 Answers

Sorry I'm so late, I just realized I can help you.

What you need to use is UIKeyCommand. Check this out: http://nshipster.com/uikeycommand/

Note that to detect arrow key presses you'll need input: UIKeyInputLeftArrow instead of input: "j" (or equiv.) when that shows up. You'll also want to have no modifiers (so the user won't have to press CMD-left arrow): please refer to Key Commands with no modifier flags—Swift 2.

Basically, you'll want something along the lines of this after (outside) your 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.   
}

I hope this helps, comment back @owlswipe if you need more help or something isn't right.

like image 82
owlswipe Avatar answered Nov 03 '22 02:11

owlswipe