Geo*_*che 41
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)
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)
| 归档时间: |
|
| 查看次数: |
24781 次 |
| 最近记录: |