简体   繁体   English

如何从xib加载视图

[英]How to load view from xib

I have a ViewController, say VC1, in which I need to load a subview say View1, programmatically. 我有一个ViewController,比如VC1,我需要以编程方式加载一个子视图,例如View1。

I have a xib file named View1.xib, whose file owner is View1. 我有一个名为View1.xib的xib文件,其文件所有者是View1。

Can anyone tell me how to load View1? 谁能告诉我如何加载View1?

I have tried the following methods: 我尝试了以下方法:

In VC1, I call 在VC1中,我打电话

View1 view1 = [[View1 alloc] init];
[[NSBundle mainBundle] loadNibNamed:@"View1" owner:view1 options:nil];
[self.view addSubview:view1];

However, it turns out that the view1 object and the object loaded from NSBundle call are not the same one. 但是,事实证明,view1对象和从NSBundle调用加载的对象不是同一个。


Updated: 更新:

In the View1.xib file, I have some IBOutLet bounding to the View1 class, so I cannot change the file owner to VC1. 在View1.xib文件中,我有一些绑定到View1类的IBOutLet,因此我无法将文件所有者更改为VC1。

If you are just loading a UIView subclass that has it's layout defined in a xib then you don't need to set File's owner. 如果您只是加载一个UIView子类,它具有在xib中定义的布局,那么您不需要设置File的所有者。 Instead you should change the class of the top level object to be that of your subclass (View1) then you use 相反,您应该将顶级对象的类更改为您的子类(View1)的类,然后使用

View1 *view1 = [[NSBundle mainBundle] loadNibNamed:@"View1" owner:nil options:nil].firstObject;

Here is how to do it: 这是怎么做的:

NSArray *xib = [[NSBundle mainBundle] loadNibNamed:@"View1" owner:self options:nil];
View1 *view1 = [xib objectAtIndex:0];
[self addSubview:view1];

Note: 注意:

When building a View1.xib view in interface builder, leave default File's Owner and set view class as View1 . 在界面构建器中构建View1.xib视图时,保留默认File's Owner并将视图类设置为View1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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