停止UIKeyCommand重复操作 [英] Stop UIKeyCommand repeated actions

查看:74
本文介绍了停止UIKeyCommand重复操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If a key command is registered, it's action might be called many times if the user holds down the key too long. This can create very weird effects, like ⌘N could repeatedly open a new view many times. Is there any easy way to stop this behavior without resorting to something like a boolean "already triggered" flag?

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

Here's how I register two different key commands:

#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

A sample project can be downloaded here: TestKeyCommands.zip

推荐答案

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

In general, you don't need to deal with this, since the new view would usually become the firstReponder and that would stop the repeating. For the playSound case, the user would realize what is happening and take her finger off of the key.

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

That said, there are real cases where specific keys should never repeat. It would be nice if Apple provided a public API for that. As far as I can tell, they do not.

考虑到代码中的"//AppStore中不允许"注释,似乎可以使用私有API了.在这种情况下,您可以使用以下命令禁用对keyCommand的重复操作:

Given the '//Not allowed in the AppStore' comment in your code, it seems like you're OK using a private API. In that case, you could disable repeating for a keyCommand with:

UIKeyCommand *keyCommand =  [UIKeyCommand ...];
[keyCommand setValue:@(NO) forKey:@"_repeatable"];

这篇关于停止UIKeyCommand重复操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆