Last active
June 20, 2016 04:13
-
-
Save wujichao/9eb579ea9adb6dd5075f8696052a123a to your computer and use it in GitHub Desktop.
UIKeyCommand
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//用法 | |
xxxxxxButton.mgj_keyCommand = @"2"; | |
-> ctrl + 2 //UIKeyModifierControl | |
// UIButton+UIKeyCommand | |
static char *kKeyCommandAssociatedObjectKey; | |
@interface UIButton (UIKeyCommand) | |
@property (nonatomic, strong) NSString *mgj_keyCommand; | |
@end | |
@implementation UIButton (UIKeyCommand) | |
- (void)setMgj_keyCommand:(NSString *)mgj_keyCommand | |
{ | |
[self bk_associateCopyOfValue:mgj_keyCommand withKey:kKeyCommandAssociatedObjectKey]; | |
} | |
- (NSString *)mgj_keyCommand | |
{ | |
return [self bk_associatedValueForKey:kKeyCommandAssociatedObjectKey]; | |
} | |
@end | |
// in vc | |
- (BOOL)canBecomeFirstResponder { | |
return YES; | |
} | |
#pragma mark - 快捷键 | |
- (NSArray<UIKeyCommand *>*)keyCommands { | |
NSMutableArray *keyCommands = [@[] mutableCopy]; | |
// workaround: http://stackoverflow.com/questions/28674907/uikeycommand-with-modifier-wont-be-recognized-on-first-invocation | |
[keyCommands addObject:[UIKeyCommand keyCommandWithInput:@"" modifierFlags:UIKeyModifierControl action:@selector(keyCommand:) discoverabilityTitle:@"Types"]]; | |
for (UIView *v in self.view.subviews) { | |
if ([v isKindOfClass:[UIButton class]]) { | |
UIButton *b = (UIButton *)v; | |
if (b.mgj_keyCommand.length) { | |
[keyCommands addObject:[UIKeyCommand keyCommandWithInput:b.mgj_keyCommand modifierFlags:UIKeyModifierControl action:@selector(keyCommand:) discoverabilityTitle:[b titleForState:UIControlStateNormal]]]; | |
} | |
} | |
} | |
return keyCommands; | |
} | |
- (void)keyCommand:(UIKeyCommand *)sender { | |
NSString *input = sender.input; | |
if (!input.length) return; | |
for (UIView *v in self.view.subviews) { | |
if ([v isKindOfClass:[UIButton class]]) { | |
UIButton *b = (UIButton *)v; | |
if ([b.mgj_keyCommand isEqualToString:input]) { | |
[b sendActionsForControlEvents:UIControlEventTouchUpInside]; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment