Multiple NSAlert 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 works fine, but I don't know how to recognize which button was clicked by the user.
+3
user4226616
source
to share
2 answers
runModal
will return the permanent positional identification of the pressed button.
This is how the values ββassociated with your buttons are determined:
enum {
NSAlertFirstButtonReturn = 1000,
NSAlertSecondButtonReturn = 1001,
NSAlertThirdButtonReturn = 1002
};
So basically what you need to do:
NSModalResponse responseTag = al.runModal();
if (responseTag == NSAlertFirstButtonReturn) {
...
} else {
...
+12
source to share
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")
}
Based on this tutorial .
0
source to share