简体   繁体   中英

Handling external keyboard presses without showing keyboard on screen on iOS app

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM