NSAlert多个按钮

3 xcode button nsalert swift

我有一个带有两个按钮的NSAlert:

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

它工作得很好,但我不知道如何识别,用户按下了哪个按钮.

ser*_*gio 12

runModal将返回"在位置上识别单击按钮的常量".

是定义与按钮关联的值的方式:

enum {
   NSAlertFirstButtonReturn   = 1000,
   NSAlertSecondButtonReturn   = 1001,
   NSAlertThirdButtonReturn   = 1002
};
Run Code Online (Sandbox Code Playgroud)

所以,基本上你应该做的是:

NSModalResponse responseTag = al.runModal();
if (responseTag == NSAlertFirstButtonReturn) {
   ...
} else {
   ...
Run Code Online (Sandbox Code Playgroud)


Leo*_*eon 6

斯威夫特 4 回答:

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")
}       
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

基于本教程