Skip to content

Instantly share code, notes, and snippets.

@marteinn
Last active January 20, 2021 04:08
Show Gist options
  • Save marteinn/540cfa4282add987ee6b to your computer and use it in GitHub Desktop.
Save marteinn/540cfa4282add987ee6b to your computer and use it in GitHub Desktop.
NSAlert Example: How to show a NSAlert as a sheet in a NSView (Cocoa)
NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:@"Delete this project?"];
[alert setInformativeText:@"Deleted projects cannot be restored"];
[alert addButtonWithTitle:@"OK"];
[alert addButtonWithTitle:@"Cancel"];
[alert setAlertStyle:NSWarningAlertStyle];
[alert beginSheetModalForWindow:self.window completionHandler:^(NSModalResponse returnCode) {
if (returnCode == NSAlertSecondButtonReturn) {
NSLog(@"Delete was cancelled!");
return;
}
NSLog(@"This project was deleted!");
}];
@quantumgolem
Copy link

@marteinn is this for Swift 3? It looks like it's for Swift 2

@marteinn
Copy link
Author

@sn0wyfall Nope, this is Objective-C.

@BradleyRoss
Copy link

It appears that NSWarningAlertStyle has been deprecated

NSAlertStyle enum now has NSAlertStyleCritical, NSAlertStyleInformational, and NSAlertStyleWarning

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment