开发者

How do i implement a message box in a Cocoa application?

I have implemented delete functionality in cocoa ap开发者_JS百科plication now i want to show one message box when user click on delete button.


Take a look at NSAlert, which has a synchronous -runModal method:

NSAlert *alert = [[[NSAlert alloc] init] autorelease];
[alert setMessageText:@"Hi there."];
[alert runModal];

As Peter mentions, a better alternative is to use the alert as a modal sheet on the window, e.g.:

[alert beginSheetModalForWindow:window
              modalDelegate:self
             didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:)
                contextInfo:nil];

Buttons can be added via -addButtonWithTitle::

[a addButtonWithTitle:@"First"];
[a addButtonWithTitle:@"Second"];

The return code tells you which button was pressed:

- (void) alertDidEnd:(NSAlert *)a returnCode:(NSInteger)rc contextInfo:(void *)ci {
    switch(rc) {
        case NSAlertFirstButtonReturn:
            // "First" pressed
            break;
        case NSAlertSecondButtonReturn:
            // "Second" pressed
            break;
        // ...
    }
}


Long time has passed since the accepted answer and things have changed:

  • Swift is becoming more and more popular.
  • beginSheetModalForWindow(_:modalDelegate:didEndSelector:contextInfo:) is deprecated, we should use beginSheetModalForWindow:completionHandler: instead.

Latest code sample in Swift:

func messageBox() {
    let alert = NSAlert()
    alert.messageText = "Do you want to save the changes you made in the document?"
    alert.informativeText = "Your changes will be lost if you don't save them."
    alert.addButtonWithTitle("Save")
    alert.addButtonWithTitle("Cancel")
    alert.addButtonWithTitle("Don't Save")
    alert.beginSheetModalForWindow(window, completionHandler: savingHandler)
}

func savingHandler(response: NSModalResponse) {
    switch(response) {
    case NSAlertFirstButtonReturn:
        println("Save")
    case NSAlertSecondButtonReturn:
        println("Cancel")
    case NSAlertThirdButtonReturn:
        println("Don't Save")
    default:
        break
    }
}

In case you want a synchronous version:

func messageBox() {
    let alert = NSAlert()
    alert.messageText = "Do you want to save the changes you made in the document?"
    alert.informativeText = "Your changes will be lost if you don't save them."
    alert.addButtonWithTitle("Save")
    alert.addButtonWithTitle("Cancel")
    alert.addButtonWithTitle("Don't Save")
    let result = alert.runModal()
    switch(result) {
    case NSAlertFirstButtonReturn:
        println("Save")
    case NSAlertSecondButtonReturn:
        println("Cancel")
    case NSAlertThirdButtonReturn:
        println("Don't Save")
    default:
        break
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜