开发者

How to give focus to NSWindow loaded from NIB?

I'm using NSWindowController to load a window from a NIB. However, when I call showWindow:, the window is visua开发者_如何学Pythonlly 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:

How to give focus to NSWindow loaded from NIB?

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?


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.


Perhaps makeMainWindow: or makeKeyWindow: helps

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜