How to stop modal close button in NSWindowController?

I want to stop the modality when the user clicks the red close button in NSWindowController.

The NSWindowController has 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 press the red close button, the window closes and the modal value does not stop. I found the windowWillClose: function.

 - (void)windowWillClose:(NSNotification *)notification { if ([NSApp modalWindow] == self.window) [NSApp stopModal]; } 

but

 if ([NSApp runModalForWindow:myWindowController.window] != NSOKButton) return; 

Even if I click OK, the windowWillClose: function is called and the runModalForWindow: function always returns NSCancelButton.

I can add a member variable to myWindowController as a result of modality.

But I think that there will be another general way to solve this problem.

I want to make an easy way.

+4
source share
3 answers

It may be a little late, but I just found this question, trying to find the answer for myself. And this is what is said in official documents: there is an event handler - (BOOL)windowShouldClose:(id)sender , which is not called when you close the window [window close]. It is called only when using the red close button or the [window performClose:] selector. So the solution is to implement windowShouldClose: instead of windowWillClose: in your subclass of NSWindowController.

+3
source

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
source

According to NSapplication class reference endSheet: methods in NSApplication will be deprecated at 10.10 (Mavericks). Apple recommends using the NSWindow beginSheet: and endSheet: methods, so if you are trying to reject NSWindowController from your NSWindowController subclass, you should use this code snippet

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

It uses the NSWindow sheetParent property to call endSheet: and passes your subclass as an argument. You can also use NSWindow endSheet: returnCode: if you want to specify a return code. Tested on OSX 10.9 / Xcode 6.1.1

0
source

All Articles