Mac开发_使NSTextField支持Cmd+C/V快捷键复制、粘贴

  • NSTextField+Copypast.h

@interface NSTextField (Copypast)

@end
  • NSTextField+Copypast.m

@implementation NSTextField (Copypast)

- (BOOL)performKeyEquivalent:(NSEvent *)event {
    if (([event modifierFlags] & NSEventModifierFlagDeviceIndependentFlagsMask) == NSEventModifierFlagCommand) {
        // The command key is the ONLY modifier key being pressed.
        if ([[event charactersIgnoringModifiers] isEqualToString:@"x"]) {
            return [NSApp sendAction:@selector(cut:) to:[[self window] firstResponder] from:self];
        } 
        else if ([[event charactersIgnoringModifiers] isEqualToString:@"c"]) {
            return [NSApp sendAction:@selector(copy:) to:[[self window] firstResponder] from:self];
        } 
        else if ([[event charactersIgnoringModifiers] isEqualToString:@"v"]) {
            return [NSApp sendAction:@selector(paste:) to:[[self window] firstResponder] from:self];
        } 
        else if ([[event charactersIgnoringModifiers] isEqualToString:@"a"]) {
            return [NSApp sendAction:@selector(selectAll:) to:[[self window] firstResponder] from:self];
        }
    }
    return [super performKeyEquivalent:event];
}

@end
  • performKeyEquivalent: 为系统自动调用的方法,在需要使用快捷键复制、粘贴的地方导入这个分类,NSTextField就可以支持复制粘贴了。
posted @ 2024-06-16 17:55  CH520  阅读(20)  评论(0编辑  收藏  举报