如何在Cocoa应用程序中实现消息框?

mik*_*ede 20 cocoa

我已经在cocoa应用程序中实现了删除功能,现在我想在用户点击删除按钮时显示一个消息框.

Geo*_*che 41

看看NSAlert,它有一个同步-runModal方法:

NSAlert *alert = [[[NSAlert alloc] init] autorelease];
[alert setMessageText:@"Hi there."];
[alert runModal];
Run Code Online (Sandbox Code Playgroud)

正如彼得所提到的,更好的选择是将警报用作窗口上的模态表,例如:

[alert beginSheetModalForWindow:window
              modalDelegate:self
             didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:)
                contextInfo:nil];
Run Code Online (Sandbox Code Playgroud)

按钮可以通过-addButtonWithTitle:以下方式添加:

[a addButtonWithTitle:@"First"];
[a addButtonWithTitle:@"Second"];
Run Code Online (Sandbox Code Playgroud)

返回代码告诉您按下了哪个按钮:

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

  • 更好的是,将警报作为包含删除按钮的窗口上的工作表开始.这样,用户可以继续使用应用程序中的任何其他窗口. (3认同)

Tyl*_*ong 10

自已接受的答案已经过去很长时间了,事情发生了变化:

  • 斯威夫特正变得越来越受欢迎.
  • beginSheetModalForWindow(_:modalDelegate:didEndSelector:contextInfo:)不推荐使用,我们应该使用beginSheetModalForWindow:completionHandler:.

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
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你想要一个同步版本:

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
    }
}
Run Code Online (Sandbox Code Playgroud)