Giorgio Doganiero
Giorgio Doganiero

Reputation: 143

UIKeyCommand action not being called

I'm trying to add keyboard shortcuts to my app and I'm having a problem with the action of the UIKeyCommand not being called.

I got a UIViewController that that is overriding the KeyCommands.

- (BOOL)becomeFirstResponder
{
return YES;
}

- (NSArray<UIKeyCommand *> *)keyCommands
{
return self.keyCommandManager.keyShortcutsArray;
}

I also have a KeyCommandManager class of NSObject which has two methods one that sets the keyShortcutsArray depending on the state of my app and the other one is the method that should be tigger by the UIKeyCommands.

- (void)setKeyShortcutsOfType:(ShortcutType)shortcutType
{
    switch(shortcutType)
    {
    case PlaybackPreviewShortcut:
        self.keyShortcutsArray = @[[UIKeyCommand keyCommandWithInput:@" " modifierFlags:0 action:@selector(keyShortcutActions:) discoverabilityTitle:@"Toggle playback preview"]];
        break;
    default:
        self.keyShortcutsArray = @[];
        break;
}

- (void)keyShortcutActions:(UIKeyCommand)sender
{
    NSLog(@"#### This method is not being called by the space key shortcut");
}

Currently when a key is pressed the KeyCommand override method is getting the correct array. However the selector of those keys are not working and the keyShortcutActions method is not being called.

Upvotes: 0

Views: 1889

Answers (1)

DonMag
DonMag

Reputation: 77423

From Apple's docs:

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.

Your keyCommandManger instance of NSObject is not in the responder chain -- the view controller is.

If you put this method:

- (void)keyShortcutActions:(UIKeyCommand)sender
{
    NSLog(@"#### This method IS being called (in view controller) by the space key shortcut");
}

you should see it being triggered.

If you want your "action" code to be contained in keyCommandManger, you could forward the event to your manager object. Or, you could try to change your manager class to inherit from UIResponder -- but reliably getting it into the chain is the tough part.

Upvotes: 2

Related Questions