Create an NSAlert with Swift Create an NSAlert with Swift swift swift

Create an NSAlert with Swift


beginSheetModalForWindow:modalDelegate is deprecated in OS X 10.10 Yosemite.

Swift 2

func dialogOKCancel(question: String, text: String) -> Bool {    let alert: NSAlert = NSAlert()    alert.messageText = question    alert.informativeText = text    alert.alertStyle = NSAlertStyle.WarningAlertStyle    alert.addButtonWithTitle("OK")    alert.addButtonWithTitle("Cancel")    let res = alert.runModal()    if res == NSAlertFirstButtonReturn {        return true    }    return false}let answer = dialogOKCancel("Ok?", text: "Choose your answer.")

This returns true or false according to the user's choice.

NSAlertFirstButtonReturn represents the first button added to the dialog, here the "OK" one.

Swift 3

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.")

Swift 4

We now use enums for the alert's style and the button selection.

func dialogOKCancel(question: String, text: String) -> Bool {    let alert = NSAlert()    alert.messageText = question    alert.informativeText = text    alert.alertStyle = .warning    alert.addButton(withTitle: "OK")    alert.addButton(withTitle: "Cancel")    return alert.runModal() == .alertFirstButtonReturn}let answer = dialogOKCancel(question: "Ok?", text: "Choose your answer.")


I think this may work for you...

let a = NSAlert()a.messageText = "Delete the document?"a.informativeText = "Are you sure you would like to delete the document?"a.addButtonWithTitle("Delete")a.addButtonWithTitle("Cancel")a.alertStyle = NSAlert.Style.WarningAlertStylea.beginSheetModalForWindow(self.view.window!, completionHandler: { (modalResponse) -> Void in    if modalResponse == NSAlertFirstButtonReturn {        print("Document deleted")    }})


Updated Jose Hidalgo's answer for Swift 4:

let a: NSAlert = NSAlert()a.messageText = "Delete the document?"a.informativeText = "Are you sure you would like to delete the document?"a.addButton(withTitle: "Delete")a.addButton(withTitle: "Cancel")a.alertStyle = NSAlert.Style.warninga.beginSheetModal(for: self.window!, completionHandler: { (modalResponse: NSApplication.ModalResponse) -> Void in    if(modalResponse == NSApplication.ModalResponse.alertFirstButtonReturn){        print("Document deleted")    }})