我已经在cocoa应用程序中实现了删除功能,现在我想在用户点击删除按钮时显示一个消息框。
答案 0 :(得分:41)
NSAlert *alert = [[[NSAlert alloc] init] autorelease];
[alert setMessageText:@"Hi there."];
[alert runModal];
正如彼得所提到的,更好的选择是在窗口上使用警告as a modal sheet,例如:
[alert beginSheetModalForWindow:window
modalDelegate:self
didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:)
contextInfo:nil];
可以通过-addButtonWithTitle:
添加按钮:
[a addButtonWithTitle:@"First"];
[a addButtonWithTitle:@"Second"];
返回代码告诉您按下了哪个按钮:
- (void) alertDidEnd:(NSAlert *)a returnCode:(NSInteger)rc contextInfo:(void *)ci {
switch(rc) {
case NSAlertFirstButtonReturn:
// "First" pressed
break;
case NSAlertSecondButtonReturn:
// "Second" pressed
break;
// ...
}
}
答案 1 :(得分:9)
自已接受答案以来已经过了很长时间,情况发生了变化:
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
}
}
如果您想要同步版本:
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
}
}