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.
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.
You can try like this
- (IBAction)okButtonClicked:(id)sender
{
[NSApp stopModalWithCode:NSOKButton];
[NSApp endSheet:self.window];
}
- (IBAction)cancelButtonClicked:(id)sender
{
[NSApp stopModalWithCode:NSCancelButton];
[NSApp endSheet:self.window];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With