If you’re creating a macOS program, you may want to display a dialog box on the screen to alert the user of something, such as an error message of some kind. The simplest way to create a dialog is to use the NSAlert class like this:
If you create a push button on a window and store the above code in an IBAction method for This code creates a simple dialog that looks like this:
The messageText property defines the bold text and the informativeText property defines the text that appears underneath.
As an alternative to displaying a modal dialog, you can also display a sheet instead by using this code:
This creates a sheet like this:
A simple dialog that displays a message is fine. When the user wants to dismiss the dialog, he or she can just click the OK button. However in many cases, you may want to add up to three buttons on a dialog with custom text. To do that, you need to use the addButton method like this:
To determine which button the user clicked, you need to use a switch statement. If you created a modal dialog using the runModal() method, your switch statement might look like this:
So if you placed a push button on a window, and created an IBAction method to display a dialog by clicking this push button, your entire code might look like this:
To determine which button the user clicked if you created a sheet, your switch statement would look slightly differently:
If you created a push button on a window with an IBAction method to open a sheet, your entire IBAction method code might look like this:
By using the NSAlert class, you an easily create and display dialogs as modal dialog boxes or as a sheet. You an also customize the number of buttons (up to three) and retrieve which button the user clicked on.