停止UIKeyCommand重复操作

Bre*_*ent 4 iphone ipad ios uikeycommand

如果注册了按键命令,则如果用户按住按键时间过长,则可能多次调用该操作。这会产生非常奇怪的效果,就像?N可以多次重复打开新视图一样。是否有任何简单的方法可以停止这种行为,而无需诉诸布尔值“已经触发”标志?

这是我注册两个不同的键盘命令的方法:

#pragma mark - KeyCommands

- (BOOL)canBecomeFirstResponder {
    return YES;
}

- (NSArray<UIKeyCommand *>*)keyCommands {
    return @[
             [UIKeyCommand keyCommandWithInput:@"O" modifierFlags:UIKeyModifierCommand action:@selector(keyboardShowOtherView:) discoverabilityTitle:@"Show Other View"],
             [UIKeyCommand keyCommandWithInput:@"S" modifierFlags:UIKeyModifierCommand action:@selector(keyboardPlaySound:) discoverabilityTitle:@"Play Sound"],
             ];
}

- (void)keyboardShowOtherView:(UIKeyCommand *)sender {
    NSLog(@"keyboardShowOtherView");
    [self performSegueWithIdentifier:@"showOtherView" sender:nil];
}

- (void)keyboardPlaySound:(UIKeyCommand *)sender {
    NSLog(@"keyboardPlaySound");
    [self playSound:sender];
}

#pragma mark - Actions

- (IBAction)playSound:(id)sender {
    AudioServicesPlaySystemSound(1006); // Not allowed in the AppStore
}
Run Code Online (Sandbox Code Playgroud)

可以在此处下载示例项目:TestKeyCommands.zip

Han*_*ans 6

我稍微修改了一下@Ely的答案:

extension UIKeyCommand {
    var nonRepeating: UIKeyCommand {
        let repeatableConstant = "repeatable"
        if self.responds(to: Selector(repeatableConstant)) {
            self.setValue(false, forKey: repeatableConstant)
        }
        return self
    }
}
Run Code Online (Sandbox Code Playgroud)

现在您可以编写更少的代码。例如,如果只是var keyCommands: [UIKeyCommand]?通过返回静态列表来覆盖它,则可以像这样使用:

override var keyCommands: [UIKeyCommand]? {
    return [
        UIKeyCommand(...),
        UIKeyCommand(...),
        UIKeyCommand(...),

        UIKeyCommand(...).nonRepeating,
        UIKeyCommand(...).nonRepeating,
        UIKeyCommand(...).nonRepeating,
    ]
}
Run Code Online (Sandbox Code Playgroud)

这使得前三个命令重复(例如增加字体大小),而后三个命令不重复(例如发送电子邮件)。

适用于Swift 4、iOS 11


Ric*_*ers 5

通常,您不需要处理此问题,因为新视图通常将成为firstReponder并停止重复。对于playSound情况,用户将意识到发生了什么,并将手指从键上移开。

就是说,在实际情况下,特定的密钥永远都不应重复。如果Apple为此提供公共API,那就太好了。据我所知,他们没有。

给定代码中的“ // AppStore中不允许”注释,您似乎可以使用私有API。在这种情况下,您可以使用以下命令禁用对keyCommand的重复:

UIKeyCommand *keyCommand =  [UIKeyCommand ...];
[keyCommand setValue:@(NO) forKey:@"_repeatable"];
Run Code Online (Sandbox Code Playgroud)

  • 疯狂的是,这不是公共API的一部分。谢谢您的帮助! (2认同)