簡體   English   中英

NSAlert 多個按鈕

[英]NSAlert multiple buttons

我有一個帶有兩個按鈕的 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 {
   ...

斯威夫特 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()
    }
  } 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM