Accessing NSAlert Buttons

Joined
Jun 8, 2013
Messages
158
Reaction score
0
Points
16
Location
Būr said,Egypt
Your Mac's Specs
MacBook Pro (i5)
I'm wondering,how to Write codes to the Buttons that appears at the Alert Message,as i want to do a specific action with these buttons.
 
Joined
Aug 13, 2011
Messages
200
Reaction score
7
Points
18
Location
West Sussex
The NSAlert's buttons return an integer, depending on which button is clicked, so you should use an if end if condition check like this.

Code:
NSAlert *alert = [[NSAlert alloc] init];
[alert addButtonWithTitle:@"Delete"];
[alert addButtonWithTitle:@"Cancel"];
[alert setMessageText:@"Delete the record?"];
[alert setInformativeText:@"Deleted records cannot be restored."];
[alert setAlertStyle:NSWarningAlertStyle];

if ([alert runModal] == NSAlertFirstButtonReturn) {
    // Delete button clicked.
} else {
    // Cancel button clicked.
}

Or.

Code:
NSAlert *alert = [[NSAlert alloc] init];
[alert addButtonWithTitle:@"Yes"];
[alert addButtonWithTitle:@"No"];
[alert addButtonWithTitle:@"Cancel"];
[alert setMessageText:@"Answer this question?"];
[alert setAlertStyle:NSWarningAlertStyle];

NSInteger result = [alert runModal];

if ( result == NSAlertFirstButtonReturn ) {
        // Yes button clicked 
} else if ( result == NSAlertSecondButtonReturn ) {
        // No button clicked
} else if ( result == NSAlertThirdButtonReturn ) {
        // Cancel button clicked
}

If you use the class method.
+ (NSAlert *)alertWithMessageText:(NSString *)messageTitle defaultButton:(NSString *)defaultButtonTitle alternateButton:(NSString *)alternateButtonTitle otherButton:(NSString *)otherButtonTitle informativeTextWithFormat:(NSString *)informativeText
To create your alert panel.

Then you can check the NSAlertDefaultReturn = 1, NSAlertAlternateReturn = 0, NSAlertOtherReturn = -1, or NSAlertErrorReturn = -2 to check for an error, in the same way as the above examples.

Hope this helps.

Regards Mark
 

Shop Amazon


Shop for your Apple, Mac, iPhone and other computer products on Amazon.
We are a participant in the Amazon Services LLC Associates Program, an affiliate program designed to provide a means for us to earn fees by linking to Amazon and affiliated sites.
Top