我想在 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 的更新
斯威夫特 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.")
分别选择“确定”或“取消”时,答案将为真或假。