Modal Window in Cocoa

jdelaune picture jdelaune · Jan 1, 2011 · Viewed 12.1k times · Source

I'm trying to create a custom modal window and here is the code I have so far:

NSWindowController *modalSheet = [[NSWindowController alloc]
initWithWindowNibName:@"MyCustomWindow" owner:self];

[NSApp beginSheet:[modalSheet window]
 modalForWindow:[self windowForSheet]
  modalDelegate:nil
 didEndSelector:nil
    contextInfo:nil];

The window pops up fine but it's not modal e.g. you can still do things to the parent window where the requests come from. This method is called from an NSDocument object.

I've tried to read: Using Custom Sheets

However i'm not sure what myCustomSheet is as it's not declared anywhere. I assume it's an NSWindow instance variable.

I just can't understand why it's not modal. Any help would be much appreciated. Thanks

Answer

Nuzhdin Vladimir picture Nuzhdin Vladimir · Mar 20, 2015

Hope this helps. To run your window controller always modal. Create your own subclass of NSWindowController and add this two methods.

- (void)windowDidLoad
{
    [super windowDidLoad];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{//TODO
        [[NSApplication sharedApplication] runModalForWindow:self.window];
    });
}

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