13

I am trying to open a NSWindow using the following code:

NSWindowController *window = [[NSWindowController alloc] initWithWindowNibName:@"MainWindow"];
[window showWindow:nil];

The window opens okay but the previous window is still the mainWindow and in focus. I have tried the following code to force the main window and it doesn't work. The window still has a disabled title bar and isn't accepting key events etc.

[self.window makeKeyAndOrderFront:self];
[self.window makeMainWindow];

The only way I seem to be able to get the previous window to lose focus is if I close the window after calling showWindow: with [[NSApp mainWindow] close];

Any ideas?

Luke
  • 6,195
  • 11
  • 57
  • 85
  • 4
    Not sure why I received a -1 here, anyone let me know how I could improve the question? – Luke May 14 '10 at 02:33

2 Answers2

13

makeKeyAndOrderFront: is the way to go. Are you sure that self.window and window refer the same object?

Nikolai Ruhe
  • 81,520
  • 17
  • 180
  • 200
  • Thanks but it still doesn't work. I added the [window makeKeyAndOrderFront:self]; call straight after the showWindow: and it still doesn't work. Should I be calling this somewhere else? – Luke May 12 '10 at 10:39
  • `makeKeyAndOrderFront:` is the right method. It shouldn't matter where you call it. Something else is the problem. For instance, the main window might be modal, or something is refusing to give up first responder status. – Tom Dalling May 12 '10 at 12:05
  • 1
    Yes, there was a problem within the nib, see my answer for the solution. – Luke May 12 '10 at 15:25
  • This worked fine along with showWindow: once the nib was setup correctly. – Luke May 14 '10 at 02:34
  • @TylerA. See my answer below – Luke Apr 02 '17 at 11:04
8

I resolved the issue by assigning the WindowController to the nib File Owner, instead of having a separate NSWindowController object within the nib.

Luke
  • 6,195
  • 11
  • 57
  • 85
  • I would like to add one point to this, I forgot to connect the window outlet to my NSWindow in Interface Builder. This led to the code not working for me, so to anyone reading this, don't forget to connect the window outlet. A simple mistake, but one that can leave you frustrated for ages lol – Supertecnoboff Jun 27 '17 at 20:44
  • Obviously a very old answer, but if anyone could translate this sentence into an image of what this looks like (as opposed to what I think it should look like, which is obviously wrong because it doesn't work), it would be super helpful. – Graham Leggett Feb 20 '22 at 22:04