开发者

How do I load a nib file from Code?

I created a custom view in interface builder with a few buttons in it. I created a class 开发者_高级运维in code for it as the "Files owner" to connect the buttons to action methods.

How do I use this class then?

I cannot just do it like this...

StartScreen *ss = [[StartScreen alloc] initWithFrame: ...];
[self.window.contentView addSubView: ss];
...

because this only produces an empty view. (of course: the StartScreen class doesn't know anything about the nib file yet.)

What I want to do is something like:

StartScreen *ss = LoadCustomViewFromNib(@"StartScreen");
[self.window.contentView addSubView: ss];

or maybe i have to say something like

[self iWannaBeANibWithName: @"StartScreen"];

in the constructor of StartScreen?

pls help... (btw I am developing for Mac OS X 10.6)


One option is to make StartScreen a subclass of NSViewController, maybe changing its name to StartScreenController. This is a potentially more modular solution in case you have IBActions in your nib file and/or you want to place view controlling code in its own class.

  1. Declare StartScreenController as a subclass of NSViewController
  2. Declare IBOutlets in StartScreenController if needed
  3. Set the nib file’s owner class to be StartScreenController
  4. Connect the file’s owner view outlet to the view object, and other outlets if needed

Then:

StartScreenController *ss = [[StartScreenController alloc] initWithNibName:@"nibname" bundle:nil];    
[self.window.contentView addSubView:ss.view];
…

If you’re not using garbage collection, don’t forget to release ss when it’s not needed any longer.


The Nib loading functions are part of the NSBundle class. You can use it like this...

@implementation StartScreen
- (id) init {
    if ((self = [super init])) {
        if (![NSBundle loadNibNamed:@"StartScreen" owner:self])
            // error
        // continue initializing
    }
    return self;
}

See NSBundle Additions reference.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜