首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSAlert多个按钮

NSAlert多个按钮
EN

Stack Overflow用户
提问于 2015-01-10 14:23:20
回答 3查看 6.7K关注 0票数 9

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

代码语言:javascript
复制
var al = NSAlert()
al.informativeText = "You earned \(finalScore) points"
al.messageText = "Game over"
al.showsHelp = false
al.addButtonWithTitle("New Game")
al.runModal()

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-01-10 14:34:02

runModal将返回“单击的位置标识按钮的常量。”

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

代码语言:javascript
复制
enum {
   NSAlertFirstButtonReturn   = 1000,
   NSAlertSecondButtonReturn   = 1001,
   NSAlertThirdButtonReturn   = 1002
};

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

代码语言:javascript
复制
NSModalResponse responseTag = al.runModal();
if (responseTag == NSAlertFirstButtonReturn) {
   ...
} else {
   ...
票数 17
EN

Stack Overflow用户

发布于 2019-04-03 13:51:33

Swift 4回答:

代码语言:javascript
复制
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")
}       

基于本教程

票数 8
EN

Stack Overflow用户

发布于 2019-12-09 09:18:49

代码语言:javascript
复制
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()
    }
  } 
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27877216

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档