5

I am currently displaying a modal window by using this code:

[[NSApplication sharedApplication] runModalForWindow:mainWindow];

However, when I close this window, the other windows are still inactive. How do I run the stopModal method when the window is closed using the "red x"?

Thank you,

Michael

4 Answers 4

10

You can create a delegate for the window and have it respond to either the
-(void)windowWillClose:(NSNotification *)notification or the
- (void)windowShouldClose:(NSNotification *)notification methods like so:

- (void)windowWillClose:(NSNotification *)notification {
   [[NSApplication sharedApplication] stopModal];
}

See Mac Dev Center: NSWindowDelegate Protocol Reference

2

If you have a dialog that applies to a specific window, then you probably shouldn't be using a modal dialog but a sheet. Modal dialogs should be avoided if possible. If you use a sheet then the problem that you're experiencing will no longer be an issue.

- (void)showSheet:(id)sender
{
    [NSApp beginSheet:yourModalWindow 
        modalForWindow:windowThatSheetIsAttachedTo
        modalDelegate:self
        didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:) 
           contextInfo:nil];
}

- (void)sheetDidEnd:(NSWindow *)sheet returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo
{
    [sheet orderOut:self];
    [NSApp endSheet:sheet];
}
0

Along with Randall's answer you can link the controller class as the delegate for the window defined in your .xib file.

You can handle the

[[NSApplication sharedApplication] stopModal];

in either

  • -(void)performClose:(id)sender

  • -(void)windowWillClose:(NSNotification *)notification

methods.

0

Swift 4 (note that the previous methods are deprecated):

window.beginSheet(self.uiSettingsPanel, completionHandler: {response in
        NSLog("Finished sheet, response: \(response)")
})

where self.uiSettingsPanel is the instance of the NSPanel subclass. Then, within the NSPanel sub-class for the sheet, close it with something like

@IBAction func buttonOK(_ sender: NSButton) {
    self.sheetParent!.endSheet(self, returnCode: .OK)
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.