IOS开发

iOS使用UIKeyCommand监听外接键盘按键事件

2019-06-21  本文已影响0人  CCyber

keyCommands


Declaration

@interface UIResponder (UIResponderKeyCommands)
@property (nullable,nonatomic,readonly) NSArray<UIKeyCommand *> *keyCommands NS_AVAILABLE_IOS(7_0); // returns an array of UIKeyCommand objects<
@end

Discussion

A responder object that supports hardware keyboard commands can redefine this property and use it to return an array of UIKeyCommand objects that it supports. Each key command object represents the keyboard sequence to recognize and the action method of the responder to call in response.

The key commands you return from this method are applied to the entire responder chain. When an key combination is pressed that matches a key command object, UIKit walks the responder chain looking for an object that implements the corresponding action method. It calls that method on the first object it finds and then stops processing the event.


实例代码

@interface CYExternalKeyboardTextView : UITextView
@end

@implementation CYExternalKeyboardTextView
- (NSArray<UIKeyCommand *> *)keyCommands {
    NSMutableArray *keys = [NSMutableArray new];
    //按键A
    [keys addObject:[UIKeyCommand keyCommandWithInput:@"a" modifierFlags:0 action:@selector(keyAction:)]];
    //按键shift, 按住的话会不停执行keyAction:
    [keys addObject:[UIKeyCommand keyCommandWithInput:@"" modifierFlags:UIKeyModifierShift action:@selector(keyAction:)]];

    //按键shift, 按住的话只执行一次keyAction
    {
        UIKeyCommand *onceShift = [UIKeyCommand keyCommandWithInput:@"" modifierFlags:UIKeyModifierShift action:@selector(keyAction:)]];
        [onceShift setValue:@(NO) forKey:@"repeatable"];
        [keys addObject:onceShift];
    }
    //组合键shift + A
    [keys addObject:[UIKeyCommand keyCommandWithInput:@"a" modifierFlags:UIKeyModifierShift action:@selector(keyAction:)]];
    //组合键ctrl + shift + A
    [keys addObject:[UIKeyCommand keyCommandWithInput:@"a" modifierFlags:UIKeyModifierControl | UIKeyModifierShift action:@selector(keyAction:)]];
    return keys;
}

- (void)keyAction:(UIKeyCommand *)keyCommand {
    //
}
@end

各按键对应input

上、下、左、右和esc

UIKIT_EXTERN NSString *const UIKeyInputUpArrow         NS_AVAILABLE_IOS(7_0);
UIKIT_EXTERN NSString *const UIKeyInputDownArrow       NS_AVAILABLE_IOS(7_0);
UIKIT_EXTERN NSString *const UIKeyInputLeftArrow       NS_AVAILABLE_IOS(7_0);
UIKIT_EXTERN NSString *const UIKeyInputRightArrow      NS_AVAILABLE_IOS(7_0);
UIKIT_EXTERN NSString *const UIKeyInputEscape          NS_AVAILABLE_IOS(7_0);

其他按键参考ASCII


image.png

例如

//空格
NSString *space = [NSString stringWithFormat:@"%c",32];
//回车
NSString *enter = [NSString stringWithFormat:@"%c",13];
//Tab
NSString *tab = [NSString stringWithFormat:@"%c",9];
//1
NSString *one = [NSString stringWithFormat:@"%c",49];

备注

  1. 部分按键、组合键在系统层被截断,无法监听,如F1~F12,command+c、command+v等。
  2. 无法区分按键的按下和松开
上一篇 下一篇

猜你喜欢

热点阅读