简体   繁体   中英

Initializing a xib view as a subview of another NSView

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM