5
votes

I have a dialog window that can be cancelled through a custom Cancel button or using the system red window button. I need to perform some simple logic when the dialog is cancelled. How do I detect that the user has pressed the red button?

I know I can detect the window being closed using the -windowWillClose: delegate callback. But this callback is also called when I close the window programmatically after the dialog succeeds. I also know I could simply set up a BOOL flag, but is there a better solution? It would be best if I could detect the red button activation.

1
Having both a Cancel button and a close button is not correct UI (at least, not on the Mac). In dialogs, buttons are present so they are sufficient. In this case there should be no enabled red button in the window frame; in Cocoa this is achieved by setting the window's mask.Kevin Grant

1 Answers

14
votes

Define close button:

NSButton *closeButton = [self standardWindowButton:NSWindowCloseButton];

Connect close button to custom selector:

[closeButton setTarget:self.delegate];
[closeButton setAction:@selector(closeThisWindow)]; 

Run specific code and close window manually.

-(void)closeThisWindow {

    //
    // The NSWindowCloseButton has been clicked.
    // Code to be run before the window closes.
    //

    [self close]; 
}