0

NSWindowController サブクラスで使用windowShouldClose:して、[保存]、[キャンセル]、および [保存しない] ボタンで閉じる前に、ユーザーが変更を保存するかどうかを尋ねるシートをポップアップ表示したいと考えています。

私が直面している問題beginSheetModalForWindow:...は、戻り値の代わりにデリゲートを使用することです。

で NO を返すことができますが、パネルのデリゲートでコントローラーwindowShouldClose:に送信しても何も起こりません。[self close]

誰かがこれを行う方法を説明したり、サンプルコードの方向性を教えてくれませんか?

4

2 に答える 2

2

これは私が最終的に使用したコードです。

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;
  }
}
于 2009-06-12T16:27:59.580 に答える
2

基本的な解決策は、保存されていない変更についてウィンドウが警告したかどうかを示すブール値フラグをウィンドウに置くことです。[self close] を呼び出す前に、このフラグを true に設定します。

最後に、windowShouldClose メソッドで、フラグの値を返します。

于 2009-06-12T02:57:06.767 に答える