Much like a UIAlertView, you can run an NSAlert on Mac like this:
1 2 3 4 5 |
// run a modal alert NSAlert *alert = [[NSAlert alloc]init]; [alert addButtonWithTitle:@"Excellent"]; [alert setMessageText:@"This is your message."]; [alert runModal]; |
Or, if you prefer a much simpler one-liner you can use NSRunAlertPanel:
1 |
NSRunAlertPanel(@"Title", @"This is your message.", @"OK", nil, nil); |
Your App Icon will be displayed in the window. Here’s an example:
The result will be the same: a separate modal window is brought up, waiting for the user to dismiss it with any of the buttons. The latter method will return an NSInteger to indicate which button was pressed.
Alert Sheets
Instead of the Alert Panel, we can also run an Alert Sheet. The functionality is the same, but instead of being a floating window the Alert Sheet is attached to your main application window. This is what it looks like:
You can create Alert Sheets like this:
1 2 |
NSAlert *alertSheet = [NSAlert alertWithMessageText:@"Title goes here." defaultButton:@"OK" alternateButton:nil otherButton:nil informativeTextWithFormat:@"And your message goes here goes here. Nice."]; [alertSheet beginSheetModalForWindow:self.window modalDelegate:nil didEndSelector:nil contextInfo:nil]; |
The above method relies on a delegate to be called so you can evaluate which button was clicked. Alternatively – if you prefer blocks and evaluate the result right there and then – you can call the Alert Sheet with
1 2 3 |
[alertSheet beginSheetModalForWindow:self.window completionHandler:^(NSModalResponse returnCode) { // check returnCode here }]; |