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!");
}];
@Klaus-Valse
Copy link

I don't understand line 8 to 15. Can you please explain? I do not have a property that is called "window". What do I do? All I have is a single window application.
Kind regards

@marteinn
Copy link
Author

Hi @Klaus-Valse! In my case I'm opening a alert through a viewController, that controller has the window property.
Sorry for the late response, next time tag me so I get a notification :)

@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