我使用UIKeyCommand映射某些快捷方式(例如"b“、箭头键、"t”、"p“等)到我的UIViewController子类中的一个功能。该应用程序是一种矢量图形软件,允许在画布中添加文本对象。当编辑视图控制器中的textView或textField时,就会出现问题。当它获得第一个响应状态时,它不会接收快捷键(例如,编写"beaver“将导致"eaver")。
是否有正确的方法来处理快捷键并在单个视图控制器中使用文本对象?
发布于 2016-05-23 11:33:47
我发现最有效的解决方案是通过响应链找到活动响应器,然后检查它是UITextField/UITextView还是其他什么。如果是的话,从- (NSArray *)keyCommands方法返回零,否则返回快捷键。下面是代码本身:
@implementation UIResponder (CMAdditions)
- (instancetype)cm_activeResponder {
UIResponder *activeResponder = nil;
if (self.isFirstResponder) {
activeResponder = self;
} else if ([self isKindOfClass:[UIViewController class]]) {
if ([(UIViewController *)self parentViewController]) {
activeResponder = [[(UIViewController *)self parentViewController] cm_activeResponder];
}
if (!activeResponder) {
activeResponder = [[(UIViewController *)self view] cm_activeResponder];
}
} else if ([self isKindOfClass:[UIView class]]) {
for (UIView *subview in [(UIView *)self subviews]) {
activeResponder = [subview cm_activeResponder];
if (activeResponder) break;
}
}
return activeResponder;
}
@end这是在keyCommands方法中实现的:
- (NSArray *)keyCommands {
if ([self.cm_activeResponder isKindOfClass:[UITextView class]] || [self.cm_activeResponder isKindOfClass:[UITextField class]]) {
return nil;
}
UIKeyCommand *brushTool = [UIKeyCommand keyCommandWithInput:@"b"
modifierFlags:kNilOptions
action:@selector(brushToolEnabled)
discoverabilityTitle:NSLocalizedString(@"Brush tool", @"Brush tool")];
UIKeyCommand *groupKey = [UIKeyCommand keyCommandWithInput:@"g"
modifierFlags:UIKeyModifierCommand
action:@selector(groupKeyPressed)
discoverabilityTitle:NSLocalizedString(@"Group", @"Group")];
UIKeyCommand *ungroupKey = [UIKeyCommand keyCommandWithInput:@"g"
modifierFlags:UIKeyModifierCommand|UIKeyModifierShift
action:@selector(ungroupKeyPressed)
discoverabilityTitle:NSLocalizedString(@"Ungroup", @"Ungroup")];
return @[groupKey, ungroupKey, brushTool];
}发布于 2019-09-05 08:01:33
我的解决方案是,如果视图控制器(具有快捷的canPerformAction:withSender: )不是第一个响应程序,则重写keyCommands并返回false。这使得响应器链无法找到接受键命令的目标,而是将键按下作为常规的UIKeyInput发送到第一个响应器,并且字符出现在文本字段中。例如:
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender{
if(action == @selector(brushKeyCommand:)){
return self.isFirstResponder;
}
return [super canPerformAction:action withSender:sender];
}https://stackoverflow.com/questions/37361103
复制相似问题