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, 按住的話會不停執(zhí)行keyAction:
[keys addObject:[UIKeyCommand keyCommandWithInput:@"" modifierFlags:UIKeyModifierShift action:@selector(keyAction:)]];
//按鍵shift, 按住的話只執(zhí)行一次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
各按鍵對應(yīng)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
例如
//空格
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];
備注
- 部分按鍵沉颂、組合鍵在系統(tǒng)層被截斷蓄坏,無法監(jiān)聽京髓,如F1~F12祷愉,command+c莱找、command+v等涣仿。
- 無法區(qū)分按鍵的按下和松開