Reputation: 5597
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.
Upvotes: 1
Views: 474
Reputation: 38728
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;
Upvotes: 2
Reputation: 40038
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
.
Upvotes: 1