Initializing a xib view as a subview of another NSView

606 views Asked by At

I'm trying to learn OSX development, and I've created a view in a .xib file, and I'm trying to initialize and then add this view as a subview. I've googled how to do this, and all of the solutions are for iOS and use a call such as MyViewClass* myViewObject = [[[NSBundle mainBundle] loadNibNamed:@"MyViewClassNib" owner:self options:nil] objectAtIndex:0], however it looks like this is not an option for OSX development. Anybody have any ideas on how to initialize the xib as a view? Thanks

1

There are 1 answers

0
rebello95 On BEST ANSWER

You could use the loadNibNamed:owner:topLevelObjects: method. Here's an example:

NSArray *views = nil;
[[NSBundle mainBundle] loadNibNamed:@"TestView1" owner:nil topLevelObjects:&views];
[self.view addSubview:[views lastObject]];

The above code will load the top-level contents of the XIB into an array. Per the documentation:

Load a nib from this bundle with the specified file name and owner. Upon success, the method returns YES and the optional out-parameter topLevelObjects is populated with the top level objects of the nib. The objects adhere to the standard Cocoa memory management rules and are autoreleased. IBOutlet properties to top level objects should be strong (retain) to demonstrate ownership and prevent deallocation. Alternatively, one may hold a strong reference to the top level objects array.