装载后指向NSWindow Xib的指针?

Bro*_*olf 5 cocoa objective-c xib

在我的下面的代码中,CustomWindow是NSWindow的子类.

CustomWindow *window = [[CustomWindow alloc] init];
if (![NSBundle loadNibNamed:@"NibName" owner:window])
[window center]; // doesn't work
Run Code Online (Sandbox Code Playgroud)

加载后如何获得控制XIB的指针,这样你可以做一些事情,例如居中的NSWindow(我的意思是位于XIB内的序列化的)?

我在这做错了什么?

Rob*_*ger 16

您应该使用NSWindowController子类.NSWindowController专门设计用于完成您想要实现的目标并解决您在使用方法直接加载nib时将遇到的几个问题NSBundle.您通常应该始终使用NSWindowController子类来管理窗口.

创建一个子类NSWindowController:

@interface MyWindowController : NSWindowController {}
@end

@implementation MyWindowController
- (id)init
{
    self = [super initWithWindowNibName:@"MyWindow"];
    if(self)
    {
        //initialize stuff
    }
    return self;
}
//this is a simple override of -showWindow: to ensure the window is always centered
-(IBAction)showWindow:(id)sender
{
    [super showWindow:sender];
    [[self window] center];
}
@end
Run Code Online (Sandbox Code Playgroud)

在Interface Builder中,设置类的文件的所有者MyWindowController和连接window的出口文件的所有者在您的笔尖的窗口对象.

然后,您可以通过执行以下操作来显示窗口:

MyWindowController* controller = [[MyWindowController alloc] init];
[controller showWindow:self];
Run Code Online (Sandbox Code Playgroud)