Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show alert pop-up in in Cocoa on macOS?

Tags:

cocoa

alert

People also ask

How do I see AppDelegate alerts?

@OrkhanAlizade create a ViewController , put your code into the ViewControllers viewDidAppear method, and in your AppDelegate , set that ViewController as the windows rootViewController (and also don't forget to create the window itself). @DánielNagy it works! Thank you!

How do I present an alert in Swift?

Adding Action Buttons to Alert Dialog To create an action button that the user can tap on, we will need to create a new instance of an UIAlertAction class and add it to our alert object. To add one more button to UIAlertController simply create a new UIAlertAction object and add it to the alert.


You can use NSAlert in cocoa. This is same as UIAlertView in ios. you can pop-up alert by this

NSAlert *alert = [NSAlert alertWithMessageText:@"Alert" defaultButton:@"Ok" alternateButton:@"Cancel" otherButton:nil informativeTextWithFormat:@"Alert pop up displayed"];
[alert runModal];

EDIT:

This is the latest used method as above method is deprecated now.

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
}

Update of @Giang


Swift 3.0 Example :

Declaration:

 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)
 }

Usage :

    showCloseAlert { answer in
        if answer {
            self.dismissViewController(self)
        }
    }