xcodebuttonswiftnsalert

NSAlert multiple buttons


I have one NSAlert with two buttons:

var al = NSAlert()
al.informativeText = "You earned \(finalScore) points"
al.messageText = "Game over"
al.showsHelp = false
al.addButtonWithTitle("New Game")
al.runModal()

It's working perfectly, but I don't know how to recognize, which button was pressed by user.


Solution

  • runModal will return "the constant positionally identifying the button clicked."

    This is how the values associated to your buttons are defined:

    enum {
       NSAlertFirstButtonReturn   = 1000,
       NSAlertSecondButtonReturn   = 1001,
       NSAlertThirdButtonReturn   = 1002
    };
    

    So, basically what you should do is:

    NSModalResponse responseTag = al.runModal();
    if (responseTag == NSAlertFirstButtonReturn) {
       ...
    } else {
       ...