我想在macOS中显示一个弹出窗口来展示信息,类似于iOS中的UIAlert或UIAlertController。
在Cocoa框架中是否有类似于iOS中UIAlertView的东西?我该如何在macOS中弹出一个警告框?
你可以在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];
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()
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的更新
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)
}
}
您可以在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.")