【问题标题】:UIKeyCommand action not being called未调用 UIKeyCommand 操作
【发布时间】:2019-03-13 14:33:10
【问题描述】:

我正在尝试将键盘快捷键添加到我的应用程序中,但我遇到了 UIKeyCommand 操作未被调用的问题。

我有一个 UIViewController 覆盖了 KeyCommands。

- (BOOL)becomeFirstResponder
{
return YES;
}

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

我还有一个 NSObject 的 KeyCommandManager 类,它有两种方法,一种是根据我的应用程序的状态设置 keyShortcutsArray,另一种是应该由 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");
}

当前,当按下某个键时,KeyCommand 覆盖方法正在获取正确的数组。但是,这些键的选择器不起作用,并且没有调用 keyShortcutActions 方法。

【问题讨论】:

    标签: ios objective-c


    【解决方案1】:

    来自苹果的docs

    您从此方法返回的关键命令将应用于整个响应程序链。当按下与按键命令对象匹配的按键组合时,UIKit 会遍历响应者链,寻找实现相应操作方法的对象。它在找到的第一个对象上调用该方法,然后停止处理该事件。

    NSObjectkeyCommandManger 实例不在在响应者链中——视图控制器在。

    如果你把这个方法:

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

    你应该看到它被触发了。

    如果您希望您的“操作”代码包含在keyCommandManger 中,您可以将事件转发给您的经理对象。或者,您可以尝试将您的管理器类更改为从 UIResponder 继承——但可靠地将其放入链中是困难的部分。

    【讨论】:

    • 谢谢,实际上我已经将方法放入 ViewController 并将选择器传递给KeyCommandManager 以使其工作。现在一切都变得更有意义了,为什么它不能反过来工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-06
    • 1970-01-01
    • 1970-01-01
    • 2017-06-03
    • 2020-07-23
    相关资源
    最近更新 更多