Search code examples
iosobjective-ckeyboard-shortcutsuikeycommand

UIKeyCommand with modifier won't be recognized on first invocation


I support keyboard shortcuts in my iOS app through serving UIKeyCommand instances from my view controller.

The following works like a charm and causes the provided selector to be invoked every time you press e:

- (BOOL)canBecomeFirstResponder {
    return YES;
}

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

However, I want the key command to be +e, or

[UIKeyCommand keyCommandWithInput:@"e" modifierFlags:UIKeyModifierCommand action:@selector(foo:)]

This still works, kind of. It won't work the first time you press +e, but it will work like a charm after that. Why does that happen and how can I fix it?


Solution

  • This is a known bug. As a workaround, you can register to respond to just the Command key by passing in an empty string and a selector that does nothing:

    [UIKeyCommand keyCommandWithInput:@""
                        modifierFlags:UIKeyModifierCommand 
                               action:@selector(doNothing:)]
    

    Then, by the time the user hits +e, it'll be the second invocation and it'll register fine.

    More information on the bug can found here on OpenRadar. It was submitted on January 27, 2015, and marked as a duplicate on February 24.