简体   繁体   English

如何在UIViewController中处理键盘快捷键

[英]How to handle Keyboard Shortcut in UIViewController

I am trying to add a keyboard shortcut for use with an external Bluetooth Keyboard to a UIViewController with no UITextField or UITextView on it. 我正在尝试将用于外部蓝牙键盘的键盘快捷方式添加到没有UITextFieldUITextViewUIViewController上。 So far I tried the following with no success 到目前为止,我尝试以下操作均未成功

- (BOOL)canBecomeFirstResponder {
    return YES;
}

- (NSArray *)keyCommands {
    return @[
             [UIKeyCommand keyCommandWithInput:@"e" modifierFlags:UIKeyModifierCommand action:@selector(handleShortcut:)]];
}

- (void)handleShortcut:(id)sender
{
    NSLog(@"%s",__FUNCTION__);
}

I also stumbled over this post with a workaround but it didn't work for me. 我还绊了这个帖子用的方法,但它并没有为我工作。 Any ideas how to handle shortcuts in a UIViewController with not textfields on it? 有什么想法如何处理没有文本字段的UIViewController中的快捷方式吗?

Make a subclass of UIView. 制作UIView的子类。 Add methods to it: 添加方法:

- (BOOL)canBecomeFirstResponder {
    return YES;
}

- (NSArray<UIKeyCommand *>*)keyCommands {
    return @[
//example shortcut CTRL+Cmnd+1
             [UIKeyCommand keyCommandWithInput:@"1" modifierFlags:UIKeyModifierCommand | UIKeyModifierControl action:@selector(pressed:)]
];
        }

Add needed selector in ("pressed:" in my case) 在中添加所需的选择器(在我的情况下为“按下:”)

Set your ViewController view class - your subclass. 设置您的ViewController视图类-您的子类。

Result - "2015-11-30 17:34:28.815 ProjectName[5204:2899520] 1" 结果-“ 2015-11-30 17:34:28.815 ProjectName [5204:2899520] 1”

A slightly old question but since Google has this link high when searching for keyboard shortcuts for a UIViewController , here's the current (Nov 2017) answer: 一个稍微古老的问题,但是由于Google在搜索UIViewController键盘快捷键时具有较高的链接,因此,这是当前(2017年11月)的答案:

UIViewController now has a simple method called -addKeyCommand: so just add your command(s) to your view controller using this method and you are good to go. UIViewController现在有一个名为-addKeyCommand:的简单方法-addKeyCommand:因此,只需使用此方法将命令添加到视图控制器中,就可以了。

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

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