【发布时间】:2013-08-27 08:48:31
【问题描述】:
我想在 macOS 中显示一个弹出窗口来显示信息,类似于 iOS 中的 UIAlert 或 UIAlertController。
他们在 Cocoa 中的任何东西是否类似于 iOS 中的 UIAlertView?如何在 macOS 中弹出警报?
【问题讨论】:
-
请向我们展示您到目前为止所做的尝试......
我想在 macOS 中显示一个弹出窗口来显示信息,类似于 iOS 中的 UIAlert 或 UIAlertController。
他们在 Cocoa 中的任何东西是否类似于 iOS 中的 UIAlertView?如何在 macOS 中弹出警报?
【问题讨论】:
您可以在可可中使用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];
【讨论】:
斯威夫特 3.0
let alert = NSAlert.init()
alert.messageText = "Hello world"
alert.informativeText = "Information text"
alert.addButton(withTitle: "OK")
alert.addButton(withTitle: "Cancel")
alert.runModal()
【讨论】:
斯威夫特 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 更新
【讨论】:
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)
}
}
【讨论】:
有一个巧妙地命名为NSAlert 的类,它可以显示一个对话框或一张表来显示您的警报。
【讨论】:
你可以在 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.")
分别选择“确定”或“取消”时,答案将为真或假。
【讨论】: