【问题标题】:How to stop modal with close button in NSWindowController?如何在 NSWindowController 中使用关闭按钮停止模式?
【发布时间】:2012-12-04 03:28:19
【问题描述】:

我想在用户单击 NSWindowController 中的红色关闭按钮时停止模式。

在 NSWindowController 中,有“确定”和“取消”按钮。

- (IBAction)okButtonClicked:(id)sender
{
    [NSApp stopModalWithCode:NSOKButton];
    [self.window close];
}

- (IBAction)cancelButtonClicked:(id)sender
{
    [NSApp stopModalWithCode:NSCancelButton];
    [self.window close];
}

当我单击红色关闭按钮时,窗口将关闭,并且模式不会停止。 我找到了 windowWillClose: 函数。

- (void)windowWillClose:(NSNotification *)notification
{
    if ([NSApp modalWindow] == self.window)
        [NSApp stopModal];
}

然而,

if ([NSApp runModalForWindow:myWindowController.window] != NSOKButton)
    return;

即使我点击 OK 按钮,windowWillClose: 函数也会被调用并且 runModalForWindow: 函数总是返回 NSCancelButton。

我可以将成员变量添加到 myWindowController 作为模态的结果。

但我认为会有另一种通用的方法来解决这个问题。

我想采取一种简单的方法。

【问题讨论】:

    标签: objective-c macos modal-dialog nswindowcontroller nspanel


    【解决方案1】:

    也许有点晚了,但我只是发现了这个问题,试图为自己找到答案。这就是官方文档中所说的:- (BOOL)windowShouldClose:(id)sender 事件处理程序在您通过 [window close] 关闭窗口时不会被调用。它仅在您使用红色关闭按钮或 [window performClose:] 选择器时调用。所以解决方案是在你的 NSWindowController 子类中实现windowShouldClose: 而不是windowWillClose:

    【讨论】:

      【解决方案2】:

      你可以这样试试

      - (IBAction)okButtonClicked:(id)sender
      {
          [NSApp stopModalWithCode:NSOKButton];
          [NSApp endSheet:self.window];
      }
      
      - (IBAction)cancelButtonClicked:(id)sender
      {
          [NSApp stopModalWithCode:NSCancelButton];
          [NSApp endSheet:self.window];
      }
      

      【讨论】:

      • 我想在用户单击 NSWindowController 中的红色关闭按钮时停止模式。
      • 你可以在Appdelegate中试试这个方法- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender { }
      【解决方案3】:

      根据 NSapplication Class Reference endSheet: NSApplication 上的方法将在 10.10 (Mavericks) 中被弃用。 Apple 建议使用 NSWindow beginSheet: 和 endSheet: 方法,因此如果您尝试从 NSWindowController 子类中关闭 NSWindowController,则应使用此代码 sn-p

      [self.window.sheetParent endSheet:self.window];
      

      它使用 NSWindow 的 sheetParent 属性来调用 endSheet: 并将您的子类的窗口作为参数传递。你也可以使用 NSWindow 的 endSheet: returnCode: 如果你想指定返回码。在 OSX 10.9 / XCode 6.1.1 上测试

      【讨论】:

        猜你喜欢
        • 2013-10-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-15
        • 1970-01-01
        相关资源
        最近更新 更多