简体   繁体   中英

How to load view from xib

I have a ViewController, say VC1, in which I need to load a subview say View1, programmatically.

I have a xib file named View1.xib, whose file owner is View1.

Can anyone tell me how to load View1?

I have tried the following methods:

In VC1, I call

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.


Updated:

In the View1.xib file, I have some IBOutLet bounding to the View1 class, so I cannot change the file owner to 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. Instead you should change the class of the top level object to be that of your subclass (View1) then you use

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 .

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