开发者

Stopping modal when window is closed (Cocoa)

开发者 https://www.devze.com 2022-12-15 08:34 出处:网络
I am currently displaying a modal window by using this code: [[NSApplication sharedApplication] runModalForWindow:mainWindow];

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 d开发者_运维问答o I run the stopModal method when the window is closed using the "red x"?

Thank you,

Michael


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


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


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.


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)
}
0

精彩评论

暂无评论...
验证码 换一张
取 消