Last active
March 8, 2020 14:15
-
-
Save tempelmann/e9ef07f606b7cce35b3ede9ecfc4e80f to your computer and use it in GitHub Desktop.
A solution to the question "How can I make the cancel button react to both the Return the the Esc keys?"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A solution to the question "How can I make the cancel button react to both the Return the the Esc keys?" | |
// | |
// See https://stackoverflow.com/a/60570407/43615 | |
#import "AppDelegate.h" | |
@interface AlertEscHandler : NSView | |
@end | |
@implementation AlertEscHandler | |
-(BOOL)performKeyEquivalent:(NSEvent *)event { | |
NSString *typed = event.charactersIgnoringModifiers; | |
NSEventModifierFlags mods = (event.modifierFlags & NSEventModifierFlagDeviceIndependentFlagsMask); | |
BOOL isCmdDown = (mods & NSEventModifierFlagCommand) != 0; | |
if ((mods == 0 && event.keyCode == 53) || (isCmdDown && [typed isEqualToString:@"."])) { // ESC key or cmd-. | |
[NSApp stopModalWithCode:1001]; // 1001 is the second button's response code | |
} | |
return [super performKeyEquivalent:event]; | |
} | |
@end | |
@implementation AppDelegate | |
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { | |
[self alertTest]; | |
[NSApp terminate:0]; | |
} | |
- (void)alertTest { | |
NSAlert *alert = [NSAlert new]; | |
alert.messageText = @"alert msg"; | |
[alert addButtonWithTitle:@"OK"]; | |
NSButton *cancelButton = [alert addButtonWithTitle:@"Cancel"]; | |
alert.window.defaultButtonCell = cancelButton.cell; | |
alert.accessoryView = [AlertEscHandler new]; | |
NSModalResponse choice = [alert runModal]; | |
NSLog (@"User chose button %d", (int)choice); | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment