Tom Coomer Tom Coomer - 7 months ago 276
Swift Question

Create an NSAlert with Swift

I have the code to create and NSAlert in Objective-C but I would now like to create it in Swift.

The alert is to confirm that the user would like to delete a document.

I would like the "delete" button to then run the delete function and the "cancel" one just to dismiss the alert.

How can I write this in Swift?

Thanks

NSAlert *alert = [[[NSAlert alloc] init] autorelease];
[alert addButtonWithTitle:@"Delete"];
[alert addButtonWithTitle:@"Cancel"];
[alert setMessageText:@"Delete the document?"];
[alert setInformativeText:@"Are you sure you would like to delete the document?"];
[alert setAlertStyle:NSWarningAlertStyle];
[alert beginSheetModalForWindow:[self window] modalDelegate:self didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:) contextInfo:nil];

Answer

beginSheetModalForWindow:modalDelegate is deprecated in OS X 10.10 Yosemite.

func dialogOKCancel(question: String, text: String) -> Bool {
    let myPopup: NSAlert = NSAlert()
    myPopup.messageText = question
    myPopup.informativeText = text
    myPopup.alertStyle = NSAlertStyle.WarningAlertStyle
    myPopup.addButtonWithTitle("OK")
    myPopup.addButtonWithTitle("Cancel")
    let res = myPopup.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.