Mac開發_使NSTextField支援Cmd+C/V快捷鍵複製、貼上

CH520發表於2024-06-16
  • 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就可以支援複製貼上了。

相關文章