劫持在雪豹的窗口关闭按钮

时间:2011-12-20 17:46:52

标签: objective-c macos cocoa nswindow

我正在开发一个基于NSDocument的应用程序,每个窗口有多个文档(标签)。这意味着我需要自己处理关闭窗口,这样我就可以在窗口关闭之前查看属于该窗口的文档。为了做到这一点,我使用standardWindowButton:NSWindowCloseButton访问了NSWindow的关闭按钮,并将此按钮的目标/操作设置为我的方法而不是标准(和私有)_close:方法。

这对Lion很有用,但在Snow Leopard上会引发问题。每当显示模式对话框时,关闭按钮将按预期禁用。但是当模态对话框被解除时,在Snow Leopard上,关闭按钮永远不会被重新启用。之后我尝试使用[closeButton setEnabled:YES]等以编程方式重新启用它,但它似乎没有任何效果。我已经确认只有当我更改了关闭按钮的目标/动作时才会发生这种情况。

关于如何在Snow Leopard上避免这种行为的任何想法,或者可能是劫持关闭按钮的另一种方法?什么是控制工具栏按钮的启用状态?也许我可以覆盖那里的东西?

1 个答案:

答案 0 :(得分:4)

我原以为你可以使用 windowShouldClose:委托方法

将Windows委托设置为AppDelegate。在AppDelegate中使用windowShouldClose:delegate方法来调用close方法并通过返回 NO 来停止窗口关闭。 在您的方法中执行所有检查,然后执行关闭:窗口。看我的例子

 NSWindow * thisWindow; //--pointer to window that will be closed
BOOL windowClose;//-- bool for confirming close of window.

- (BOOL)windowShouldClose:(id)sender{
    thisWindow =sender;//-- set thisWindow to the sender window,the one that is to be closed )
    //if (sender ==theWindow) {//--you can use this to do further checking

        if (windowClose) {//-- Close window if YES
            return YES;  
        } 
    //}


    [self performSelector:@selector(myCloseWindow) ];//go to your method
    windowClose =FALSE;//-- reset
    return NO;//do not close window here
}

- (void) myCloseWindow {
    NSLog(@"closing window");//-- do your stuff
    windowClose =TRUE;//--give the ok to close the window
    [thisWindow performClose:thisWindow];//-- perform the close, which will be redirected back to the delegate, which will now allow the window to close
}