How to stop modal with close button in NSWindowController?
macos, modal-dialog, nspanel, nswindowcontroller, objective-c
Solution
Maybe it's a little bit late, but I just found this question in attempt to find an answer for myself. And that's what is said in the official docs: there is `- (BOOL)windowShouldClose:(id)sender` event handler which is not called when you close the window by [window close]. It is only called when you use red close button or [window performClose:] selector. So the solution is to implement `windowShouldClose:` instead of `windowWillClose:` in your NSWindowController subclass.
Problem
I want to stop modal when the user clicks the red close button in NSWindowController. In the NSWindowController, there are "OK" and "Cancel" buttons. ``` - (IBAction)okButtonClicked:(id)sender { [NSApp stopModalWithCode:NSOKButton]; [self.window close]; } - (IBAction)cancelButtonClicked:(id)sender { [NSApp stopModalWithCode:NSCancelButton]; [self.window close]; } ``` And when I click the red close button, the window will close and the modal doesn't stop. I've found the windowWillClose: function. ``` - (void)windowWillClose:(NSNotification *)notification { if ([NSApp modalWindow] == self.window) [NSApp stopModal]; } ``` However, ``` if ([NSApp runModalForWindow:myWindowController.window] != NSOKButton) return; ``` Even if I click the OK button, windowWillClose: function is called and runModalForWindow: function always returns NSCancelButton. I can add the member variable into myWindowController as the result of the modal. But I think that there'll be another generic way to resolve this problem. I want to take an easy way.