雪豹上的窗口关闭按钮被劫持



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

这在Lion上工作得很好,但在Snow Leopard上它会引起问题。每当显示模态对话框时,关闭按钮将按预期禁用。但是当模态对话框被关闭时,雪豹上的关闭按钮永远不会被重新启用。我试过用[closeButton setEnabled:YES]等编程后重新启用它,但它似乎没有任何影响。我已经确认,只有当我改变了关闭按钮的目标/动作时才会发生这种情况。

关于如何在雪豹上避免这种行为,或者劫持关闭按钮的替代方法,有什么想法吗?是什么控制工具栏按钮的启用状态?也许我可以重写一些东西?

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

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

 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
}

最新更新