4
votes

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.

3

3 Answers

4
votes

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.

3
votes

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];
}
2
votes

According to NSapplication Class Reference the endSheet: methods on NSApplication will be deprecated in 10.10 (Mavericks). Apple recommends using the NSWindow beginSheet: and endSheet: methods so if you're trying to dismiss your NSWindowController from within your NSWindowController subclass you should use this code snippet

[self.window.sheetParent endSheet:self.window];

It uses NSWindow's sheetParent property to call endSheet: and passes your subclass' window as the argument. You can also use NSWindow's endSheet: returnCode: if you wish to specify the return code. Tested on OSX 10.9 / XCode 6.1.1