【问题标题】:NSAlert multiple buttonsNSAlert 多个按钮
【发布时间】:2015-03-08 18:10:09
【问题描述】:

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

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

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

【问题讨论】:

标签: xcode button swift nsalert


【解决方案1】:

runModal 将返回 "the constant positionally identifying the button clicked."

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

enum {
   NSAlertFirstButtonReturn   = 1000,
   NSAlertSecondButtonReturn   = 1001,
   NSAlertThirdButtonReturn   = 1002
};

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

NSModalResponse responseTag = al.runModal();
if (responseTag == NSAlertFirstButtonReturn) {
   ...
} else {
   ...

【讨论】:

    【解决方案2】:

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

    基于this tutorial

    【讨论】:

      【解决方案3】:
      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()
          }
        } 
      }
      

      【讨论】:

        猜你喜欢
        • 2019-04-20
        • 2013-05-13
        • 1970-01-01
        • 2011-09-04
        • 1970-01-01
        • 2018-04-21
        • 2011-12-11
        • 2014-06-16
        • 2012-10-26
        相关资源
        最近更新 更多