我需要为 NSTokenField 和解决方案实现 Command + Enter、Command + O 和 Esc 快捷键https://stackoverflow.com/a/18486965/1067147 https://stackoverflow.com/a/18486965/1067147不起作用,因为 -(void)noop:(SEL)sel 没有用。
我的方法是为层次结构中的上层类 NSView 创建类别(我也尝试为 NSTextView 但没有运气):
// NSView+WideInterpreter.h
#import <Cocoa/Cocoa.h>
#define kNotificationTokenModifier @"kNotificationTokenModifier"
#define kNotificationTokenModifier_modifier @"kNotificationTokenModifier_modifier"
typedef enum{
BMTokenModifier_CommandEnter = 10,
BMTokenModifier_CommandO,
BMTokenModifier_Esc,
BMTokenModifier_nextKeyViewActivate
} BMTokenModifier;
@interface NSView (WideInterpreter)
@end
and
NSView+WideInterpreter.m
#import "NSView+WideInterpreter.h"
@implementation NSView (WideInterpreter)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
- (void)interpretKeyEvents:(id)keyEvents{
NSMutableArray *result = [[NSMutableArray alloc] init];
for (NSEvent *theEvent in keyEvents) {
NSUInteger clearFlags = ([theEvent modifierFlags] & NSDeviceIndependentModifierFlagsMask);
BOOL commandPressed = (clearFlags == NSCommandKeyMask);
switch ([theEvent keyCode]) {
case 31:{//Ctrl+O
if (commandPressed)
[[NSNotificationCenter defaultCenter] postNotificationName:kNotificationTokenModifier
object:self
userInfo:@{kNotificationTokenModifier_modifier: @(BMTokenModifier_CommandO)}];
}break;
case 36:{//Enter
if (commandPressed)
[[NSNotificationCenter defaultCenter] postNotificationName:kNotificationTokenModifier
object:self
userInfo:@{kNotificationTokenModifier_modifier: @(BMTokenModifier_CommandEnter)}];
else
[super insertNewlineIgnoringFieldEditor:self];
}break;
case 53://Esc
[[NSNotificationCenter defaultCenter] postNotificationName:kNotificationTokenModifier
object:self
userInfo:@{kNotificationTokenModifier_modifier: @(BMTokenModifier_Esc)}];
break;
default:// allow super to handle everything else
[result addObject:theEvent];
break;
}
}
[super interpretKeyEvents:result];
}
#pragma clang diagnostic pop
@end
对于使用的作品:
[[NSNotificationCenter defaultCenter] addObserverForName:kNotificationTokenModifier
object:nil
queue:[NSOperationQueue currentQueue]
usingBlock:^(NSNotification *note) {
BMTokenModifier modifier = (BMTokenModifier)[[[note userInfo] objectForKey:kNotificationTokenModifier_modifier] integerValue];
switch (modifier) {
case BMTokenModifier_CommandEnter:
[self sendMessage];
break;
case BMTokenModifier_CommandO:
[self attachFiles];
break;
default:
break;
}
}];
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)