How to load nib file from code?

I created a custom view in the interface designer with a few buttons in it. I created a class in the code for it as a “file owner” to connect buttons to action methods.

How can I use this class?

I can't just do that ...

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

because it only creates an empty view. (of course: the StartScreen class still doesn't know anything about the nib file.)

I want to do something like:

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

or maybe I should say something like

 [self iWannaBeANibWithName: @"StartScreen"]; 

in the StartScreen constructor?

Please help ... (by the way, I'm developing for Mac OS X 10.6)

+4
source share
2 answers

One option is to make StartScreen subclass of NSViewController , possibly changing its name to StartScreenController . This is a potentially more modular solution if you have IBActions in your nib file and / or you want to put view control code in your class.

  • Declare StartScreenController as a subclass of NSViewController
  • Declare IBOutlets in StartScreenController if necessary
  • Set nib file owner class as StartScreenController
  • Connect the owner of the view file to the view object and other outputs if necessary

Then:

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

If you are not using garbage collection, remember to free ss when it is no longer needed.

+4
source

Nib boot 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 Link to NSBundle sitelinks .

+2
source

All Articles