Objective c 如何在NSWindowController中使用关闭按钮停止模式?

Objective c 如何在NSWindowController中使用关闭按钮停止模式?,objective-c,macos,modal-dialog,nswindowcontroller,nspanel,Objective C,Macos,Modal Dialog,Nswindowcontroller,Nspanel,我想在用户单击NSWindowController中的红色关闭按钮时停止模式 在NSWindowController中,有“确定”和“取消”按钮 当我单击红色关闭按钮时,窗口将关闭,模式不会停止。 我发现窗口将关闭:函数 - (void)windowWillClose:(NSNotification *)notification { if ([NSApp modalWindow] == self.window) [NSApp stopModal]; } 但是, if (

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

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

当我单击红色关闭按钮时,窗口将关闭,模式不会停止。 我发现窗口将关闭:函数

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

if ([NSApp runModalForWindow:myWindowController.window] != NSOKButton)
    return;
即使单击确定按钮,窗口也将关闭:函数被调用,runModalForWindow:函数始终返回NSCancelButton

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

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

我想走一条简单的路。

你可以这样试试

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

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

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

根据 结尾:非应用程序上的方法将在10.10(Mavericks)中被弃用。Apple建议使用NSWindow beginSheet:和endSheet:方法,因此如果您试图从NSWindowController子类中删除NSWindowController,则应使用此代码段

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

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

当用户单击NSWindowController中的红色关闭按钮时,我想停止模式。您可以在Appdelegate中尝试此方法
-(NSApplicationTerminateReply)应用程序应终止:(NSApplication*)发送方{}
[self.window.sheetParent endSheet:self.window];