I have a private iOS app that I want to control using an external keyboard connected via Bluetooth. I don't want any UITextField
or UITextView
in my app, or at least I don't want the keyboard to show all the time. Is there a way for me listen to these keyboard events from the physical keyboard? thanks.
Asked
Active
Viewed 2,307 times
2

7ball
- 2,183
- 4
- 26
- 61
-
You can use commands: http://www.thomashanning.com/uikeycommand-defining-keyboard-shortcuts/ but it only works with CMD+A_KEY – Emma Labbé Dec 04 '17 at 22:49
2 Answers
3
UIKeyCommands
To listen keys from keyboard, you can override the keyCommands
variable on your ViewController (It's an array so you can put many shortcuts):
override var keyCommands: [UIKeyCommand]? {
return [
UIKeyCommand(input: "Q",
modifierFlags: [],
action: #selector(self.close),
discoverabilityTitle: "Close app")
]
}
func close() {
exit(0)
}
Input is the key to use, for example CMD+Q (only put Q). Action is the selector to call and discoverabilityTitle is the title of the shortcut, for example "Close app". It will be displayed in iPad when the user holds the CMD key.
It only works with CMD keys and other specials keys:
UIKeyInputUpArrow
UIKeyInputDownArrow
UIKeyInputLeftArrow
UIKeyInputRightArrow
UIKeyInputEscape

Emma Labbé
- 667
- 7
- 18
-
I also try to handle keyboard event on iPad/iPhone for a game. Your solution solved my problem! Wondering if you know how to detect the "key-down" and "key-up" state. For example, a game needs to detect whether the arrow keys and Enter key are currently pressed or released, so that it can manoeuvre a spaceship or fire weapon. I have not find answer yet. – Hongkun Wang Oct 02 '19 at 00:17
0
This was helpful for me: https://www.avanderlee.com/swift/uikeycommand-keyboard-shortcuts/
I had to add the canBecomeFirstResponder override to get this to work.

Jason
- 1,323
- 14
- 19