且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将重点放在从NIB加载的NSWindow?

更新时间:2023-02-13 08:35:51



xib文件的所有者必须设置为控制器,并且(这是我不知道的部分)你必须连接控制器的 window 插入窗口本身。



完成后,它只是工作。不需要 makeKeyWindow makeMainWindow makeKeyAndOrderFront: p>

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?

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.