Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xcode/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Xcode NSAlert多个按钮_Xcode_Button_Swift_Nsalert - Fatal编程技术网

Xcode NSAlert多个按钮

Xcode NSAlert多个按钮,xcode,button,swift,nsalert,Xcode,Button,Swift,Nsalert,我有一个带两个按钮的NSAlert: var al = NSAlert() al.informativeText = "You earned \(finalScore) points" al.messageText = "Game over" al.showsHelp = false al.addButtonWithTitle("New Game") al.runModal() 它工作得很好,但我不知道如何识别用户按下了哪个按钮。runModal将返回 是如何定义与按钮关联的值: enum {

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

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

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

runModal
将返回

是如何定义与按钮关联的值:

enum {
   NSAlertFirstButtonReturn   = 1000,
   NSAlertSecondButtonReturn   = 1001,
   NSAlertThirdButtonReturn   = 1002
};
所以,基本上你应该做的是:

NSModalResponse responseTag = al.runModal();
if (responseTag == NSAlertFirstButtonReturn) {
   ...
} else {
   ...
Swift 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")
}       

基于。

可能重复的
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()
    }
  } 
}