9

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.

  • 2
    Possible duplicate of [What is the correct way for handling which button is pressed with NSAlert](https://stackoverflow.com/questions/23381971/what-is-the-correct-way-for-handling-which-button-is-pressed-with-nsalert) – Jon Schneider Nov 19 '18 at 13:24

3 Answers3

17

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 {
   ...
sergio
  • 68,819
  • 11
  • 102
  • 123
9

Swift 4 answer:

let alert = NSAlert()
alert.messageText = "Alert title"
alert.informativeText = "Alert message."
alert.addButton(withTitle: "First")
alert.addButton(withTitle: "Second")
alert.addButton(withTitle: "Third")
alert.addButton(withTitle: "Fourth")
let modalResult = alert.runModal()

switch modalResult {
case .alertFirstButtonReturn: // NSApplication.ModalResponse.alertFirstButtonReturn
    print("First button clicked")
case .alertSecondButtonReturn:
    print("Second button clicked")
case .alertThirdButtonReturn:
    print("Third button clicked")
default:
    print("Fourth button clicked")
}       

enter image description here

Based on this tutorial.

Leon
  • 3,614
  • 1
  • 33
  • 46
1
extension NSViewController {

struct CustomAlertButton {
    var title: String
    var action: () -> Void
}

func showAlert(title: String, msg: String, customActions: [CustomAlertButton] = []) {
    DispatchQueue.main.async {
        let alert = NSAlert()
        alert.messageText = title
        alert.informativeText = msg

        customActions.forEach({ item in
            alert.addButton(withTitle: item.title)
        })

        if customActions.isEmpty {
            alert.addButton(withTitle: "Ok")
        }

        let modalResult = alert.runModal()
        let index = modalResult.rawValue - 1000//according to documentation

        customActions[safe: index]?.action()
    }
  } 
}
isHidden
  • 860
  • 5
  • 16