如果注册了一个键命令,如果用户按住键的时间过长,它的操作可能会被调用多次。这会产生非常奇怪的效果,例如 ⌘N 可以多次重复打开新 View 。有什么简单的方法可以在不诉诸 bool “已触发”标志之类的情况下停止这种行为?
下面是我如何注册两个不同的键盘命令:
#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
}
可在此处下载示例项目:TestKeyCommands.zip
最佳答案
一般来说,您不需要处理这个问题,因为新 View 通常会成为 firstReponder 并且会停止重复。对于 playSound 案例,用户会意识到发生了什么,然后将手指从按键上移开。
也就是说,在某些实际情况下,特定的键永远不应该重复。如果苹果为此提供一个公共(public) API 就好了。据我所知,他们没有。
鉴于您代码中的“//AppStore 中不允许”注释,您似乎可以使用私有(private) API。在这种情况下,您可以通过以下方式禁用 keyCommand 的重复:
UIKeyCommand *keyCommand = [UIKeyCommand ...];
[keyCommand setValue:@(NO) forKey:@"_repeatable"];
关于ios - 停止 UIKeyCommand 重复 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41731442/