How to give focus to NSWindow loaded from NIB?

我怕爱的太早我们不能终老 提交于 2019-12-06 05:44:34

问题


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?


回答1:


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.




回答2:


Perhaps makeMainWindow: or makeKeyWindow: helps



来源:https://stackoverflow.com/questions/5289386/how-to-give-focus-to-nswindow-loaded-from-nib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!