简体   繁体   English

处理外部键盘按键而不在 iOS 应用程序的屏幕上显示键盘

[英]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.我有一个私人 iOS 应用程序,我想使用通过蓝牙连接的外部键盘进行控制。 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.我不希望我的应用程序中有任何UITextFieldUITextView ,或者至少我不希望键盘一直显示。 Is there a way for me listen to these keyboard events from the physical keyboard?有没有办法让我从物理键盘上收听这些键盘事件? thanks.谢谢。

UIKeyCommands 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):要从键盘监听按键,您可以覆盖 ViewController 上的keyCommands变量(它是一个数组,因此您可以放置​​许多快捷方式):

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). input是使用的键,例如CMD+Q(只放Q)。 Action is the selector to call and discoverabilityTitle is the title of the shortcut, for example "Close app". Action 是要调用的选择器,discoverabilityTitle 是快捷方式的标题,例如“关闭应用程序”。 It will be displayed in iPad when the user holds the CMD key.当用户按住 CMD 键时,它将显示在 iPad 中。

It only works with CMD keys and other specials keys:它仅适用于 CMD 键和其他特殊键:

UIKeyInputUpArrow
UIKeyInputDownArrow
UIKeyInputLeftArrow
UIKeyInputRightArrow
UIKeyInputEscape

This was helpful for me: https://www.avanderlee.com/swift/uikeycommand-keyboard-shortcuts/这对我很有帮助: https : //www.avanderlee.com/swift/uikeycommand-keyboard-shortcuts/

I had to add the canBecomeFirstResponder override to get this to work.我必须添加 canBecomeFirstResponder 覆盖才能使其工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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