问题
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:
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];
}
来源:https://stackoverflow.com/questions/11249822/how-to-detect-that-my-window-is-being-closed-using-the-red-window-button