题
我想用windowShouldClose:
在我的NSWindowController子类弹出一个表,询问用户是否希望与保存在关闭之前保存更改,取消,不保存按钮。
我运行到是beginSheetModalForWindow:...
问题使用委托,而不是一个返回值的。
我可以在windowShouldClose:
返回NO,但然后当我发送[self close]
到面板中的委托没什么控制器发生。
有人能向我解释如何做到这一点或点我的一些示例代码的方向?
解决方案
的基本解决方案是将一个布尔标志,指出该窗口是否已经警告未保存的更改在窗口上。主叫[自紧密]之前,该标志设置为真。
最后,在windowShouldClose方法,返回该标志的值。
其他提示
这是我最后使用的代码。
windowShouldCloseAfterSaveSheet_
是在我的控制器类的一个实例变量。
记住设置窗口出口,用于在IB控制器。
- (BOOL)windowShouldClose:(id)window {
if (windowShouldCloseAfterSaveSheet_) {
// User has already gone through save sheet and choosen to close the window
windowShouldCloseAfterSaveSheet_ = NO; // Reset value just in case
return YES;
}
if ([properties_ settingsChanged]) {
NSAlert *saveAlert = [[NSAlert alloc] init];
[saveAlert addButtonWithTitle:@"OK"];
[saveAlert addButtonWithTitle:@"Cancel"];
[saveAlert addButtonWithTitle:@"Don't Save"];
[saveAlert setMessageText:@"Save changes to preferences?"];
[saveAlert setInformativeText:@"If you don't save the changes, they will be lost"];
[saveAlert beginSheetModalForWindow:window
modalDelegate:self
didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:)
contextInfo:nil];
return NO;
}
// Settings haven't been changed.
return YES;
}
// This is the method that gets called when a user selected a choice from the
// do you want to save preferences sheet.
- (void)alertDidEnd:(NSAlert *)alert
returnCode:(int)returnCode
contextInfo:(void *)contextInfo {
switch (returnCode) {
case NSAlertFirstButtonReturn:
// Save button
if (![properties_ saveToFile]) {
NSAlert *saveFailedAlert = [NSAlert alertWithMessageText:@"Save Failed"
defaultButton:@"OK"
alternateButton:nil
otherButton:nil
informativeTextWithFormat:@"Failed to save preferences to disk"];
[saveFailedAlert runModal];
}
[[alert window] orderOut:self];
windowShouldCloseAfterSaveSheet_ = YES;
[[self window] performClose:self];
break;
case NSAlertSecondButtonReturn:
// Cancel button
// Do nothing
break;
case NSAlertThirdButtonReturn:
// Don't Save button
[[alert window] orderOut:self];
windowShouldCloseAfterSaveSheet_ = YES;
[[self window] performClose:self];
break;
default:
NSAssert1(NO, @"Unknown button return: %i", returnCode);
break;
}
}
不隶属于 StackOverflow