将 xib 视图初始化为另一个 NSView 的子视图

Initializing a xib view as a subview of another NSView

我正在尝试学习 OSX 开发,我在 .xib 文件中创建了一个视图,我正在尝试初始化该视图,然后将其添加为子视图。我用谷歌搜索了如何执行此操作,所有解决方案都针对 iOS 并使用 MyViewClass* myViewObject = [[[NSBundle mainBundle] loadNibNamed:@"MyViewClassNib" owner:self options:nil] objectAtIndex:0] 等调用,但看起来这不是 OSX 开发的选项。有人对如何将 xib 初始化为视图有任何想法吗?谢谢

您可以使用 loadNibNamed:owner:topLevelObjects: 方法。这是一个例子:

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

以上代码会将 XIB 的顶级内容加载到一个数组中。根据文档:

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.