5

I'm using NSWindowController to load a window from a NIB. However, when I call showWindow:, the window is visually topmost, but the focus remains where it was (instead of moving it to the new window).

It's easy to see this happening when the first window (with keyboard focus) is moved slightly, before creating the new window (via cmd+n). This is the result:

The bottom, focused window is the original window. The unfocused window on top is the newly created window.

This is the relevant code:

AppDelegate.h:

- (IBAction)newDocument:(id) sender;

AppDelegate.m:

- (IBAction)newDocument:(id) sender {
    [[[FooController alloc] init] showWindow:self];
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    [self newDocument:self];
}

FooController.h:

@interface FooController : NSWindowController { }
@end

FooController.m:

- (id)init {
    self = [super initWithWindowNibName:@"FooWindow"];
    return self;
}

FooWindow.xib:
A freshly created Window xib, without modifications.

MainMenu.xib:
The default MainMenu.xib, with its window deleted.

Calling makeKeyAndOrderFront: on the window in the controller's windowDidLoad method does not appear to focus the new window. Setting the File's owner of FooWindow.xib to FooController also did not appear to help.

What is the correct way to load and show a window from a NIB so that it does receive keyboard focus?

Edit: It looks like NSWindowController's window method returns nil, which explains why calling methods on window doesn't do anything. But why is it nil?

Zr40
  • 1,910
  • 18
  • 20

2 Answers2

11

Okay, I found the cause of this problem.

The xib's File's owner must be set to the controller, and (this is the part I didn't know about) you have to connect the controller's window outlet to the window itself.

Having done that, it just works. No makeKeyWindow, makeMainWindow or makeKeyAndOrderFront: needed.

Zr40
  • 1,910
  • 18
  • 20
  • Obviously a very old answer, but without an actual screenshot of what this looks like after it's configured correctly, this isn't specific enough. – Graham Leggett Feb 20 '22 at 22:16
1

Perhaps makeMainWindow: or makeKeyWindow: helps

lbrndnr
  • 3,361
  • 2
  • 24
  • 34
  • Calling these from `windowDidLoad` does not focus the new window. Should they be called from elsewhere, perhaps? – Zr40 Mar 13 '11 at 12:54
  • I think they should be called after the makeKeyAndOrderFront: call – lbrndnr Mar 13 '11 at 14:40
  • That's what I tried before. Whatever combination and order of `makeKeyAndOrderFront:`, `makeMainWindow` and `makeKeyWindow` I put in `windowDidLoad`, the new window does not obtain focus. – Zr40 Mar 13 '11 at 15:48