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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With