如何在macOS的Cocoa中显示警报弹出窗口?

41

我想在macOS中显示一个弹出窗口来展示信息,类似于iOS中的UIAlert或UIAlertController。

在Cocoa框架中是否有类似于iOS中UIAlertView的东西?我该如何在macOS中弹出一个警告框?


3
请展示一下您目前为止所尝试的内容。 - Kundan
6个回答

48

你可以在Cocoa中使用NSAlert,这与iOS中的UIAlertView相同。 你可以通过它弹出警告框。

NSAlert *alert = [NSAlert alertWithMessageText:@"Alert" defaultButton:@"Ok" alternateButton:@"Cancel" otherButton:nil informativeTextWithFormat:@"Alert pop up displayed"];
[alert runModal];

编辑:

这是目前最新使用的方法,因为上述方法已被弃用。

NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:@"Message text."];
[alert setInformativeText:@"Informative text."];
[alert addButtonWithTitle:@"Cancel"];
[alert addButtonWithTitle:@"Ok"];
[alert runModal];

此方法已被弃用。苹果文档引用 - “已弃用。相反,应该分配并初始化一个NSAlert对象,并根据需要设置其属性。” - Vikram Singh
1
是的,这种方法现在已经过时了。但是你仍然可以使用它,无论如何,我会编辑我的答案,提供新的显示警报的方法。 - Surjeet Singh

24

Swift 3.0

let alert = NSAlert.init()
alert.messageText = "Hello world"
alert.informativeText = "Information text"
alert.addButton(withTitle: "OK")
alert.addButton(withTitle: "Cancel")
alert.runModal()

18

Swift 5.1

func confirmAbletonIsReady(question: String, text: String) -> Bool {
    let alert = NSAlert()
    alert.messageText = question
    alert.informativeText = text
    alert.alertStyle = NSAlert.Style.warning
    alert.addButton(withTitle: "OK")
    alert.addButton(withTitle: "Cancel")
    return alert.runModal() == NSApplication.ModalResponse.alertFirstButtonReturn
}

@Giang的更新


5

Swift 3.0示例:

声明:

 func showCloseAlert(completion: (Bool) -> Void) {
        let alert = NSAlert()
        alert.messageText = "Warning!"
        alert.informativeText = "Nothing will be saved!"
        alert.alertStyle = NSAlertStyle.warning
        alert.addButton(withTitle: "OK")
        alert.addButton(withTitle: "Cancel")
        completion(alert.runModal() == NSAlertFirstButtonReturn)
 }

用法:

    showCloseAlert { answer in
        if answer {
            self.dismissViewController(self)
        }
    }

4

您可以在Swift中使用此方法。

 func dialogOKCancel(question: String, text: String) -> Bool
        {
            let alert = NSAlert()
            alert.messageText = question
            alert.informativeText = text
            alert.alertStyle = NSAlertStyle.warning
            alert.addButton(withTitle: "OK")
            alert.addButton(withTitle: "Cancel")
            return alert.runModal() == NSAlertFirstButtonReturn
        }

然后以这种方式调用它

let answer = dialogOKCancel(question: "Ok?", text: "Choose your answer.")

选中“确定”或“取消”后,答案将分别为true或false。

4

有一个名字巧妙的NSAlert类,可以显示对话框或工作表,以呈现您的警报。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接