如果注册了一个键命令,如果用户长时间按住该键,则可能会多次调用该命令的操作。这会产生非常奇怪的效果,比如⌘N可以多次重复打开一个新视图。有没有什么简单的方法来停止这种行为,而不是求助于布尔型“已触发”标志?
下面是我如何注册两个不同的key命令:
#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
发布于 2017-10-30 09:45:29
一般来说,你不需要处理这个问题,因为新的视图通常会变成firstReponder,这样就会停止重复。对于playSound,用户会意识到发生了什么,并将手指从键上移开。
这就是说,在实际情况下,特定的键永远不应该重复。如果苹果能为此提供一个公共API就太好了。据我所知,他们没有。
考虑到代码中的“//Not allowed in the API”注释,似乎可以使用私有AppStore。在这种情况下,您可以使用以下命令为keyCommand禁用重复:
UIKeyCommand *keyCommand = [UIKeyCommand ...];
[keyCommand setValue:@(NO) forKey:@"_repeatable"];发布于 2019-04-19 02:57:01
这在iOS 12中有效,与公认的答案相比,它没有那么“私密”:
let command = UIKeyCommand(...)
let repeatableConstant = "repeatable"
if command.responds(to: Selector(repeatableConstant)) {
command.setValue(false, forKey: repeatableConstant)
}https://stackoverflow.com/questions/41731442
复制相似问题