Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop modal with close button in NSWindowController?

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.

like image 789
Yun Avatar asked Jan 15 '23 20:01

Yun


2 Answers

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.

like image 160
Uniqus Avatar answered Jan 30 '23 10:01

Uniqus


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];
}
like image 21
NewStack Avatar answered Jan 30 '23 08:01

NewStack