0
votes

I have a UIView, that contains 3 other subviews. At the beginning, I do not add these 3 subviews into the UIView, instead I created them separately as follow:

enter image description here

I want to add the subview dynamically. So I try this code as follow:

Add MainView to UIViewController

UINib *nib = [UINib nibWithNibName:@"MainView" bundle:nil];
MainView* mainView = [[nib instantiateWithOwner:self options:nil] objectAtIndex:0];
[self.view addSubview:mainView];

It's ok so far. But now, in the MainView class, I add the subView, I got crash

UINib *nib = [UINib nibWithNibName:@"SubView1" bundle:nil];
SubView1* subView1 = [[nib instantiateWithOwner:self options:nil] objectAtIndex:0];
[self addSubview:subView1];

What's wrong with my code?

2
You can have 3 subviews in your main view and call that views when needed. Hide remaining ones and bringsubviewtofront the view which you want to show.Manthan

2 Answers

2
votes

I don't know why it crash cause I had never use this type. So what I suggest you try the below

UIView *mainView=[[[NSBundle mainBundle] loadNibNamed:@"yourNibName" owner:self options:nil] objectAtIndex:0];
[[self view] addSubview:mainView];

In the same way

UIView *subView1=[[[NSBundle mainBundle] loadNibNamed:@"yourNibName" owner:self options:nil] objectAtIndex:1];
[mainView addSubview:subView1];

UIView *subView2=[[[NSBundle mainBundle] loadNibNamed:@"yourNibName" owner:self options:nil] objectAtIndex:2];
[mainView addSubview:subView2];

UIView *subView3=[[[NSBundle mainBundle] loadNibNamed:@"yourNibName" owner:self options:nil] objectAtIndex:3];
[mainView addSubview:subView3];

I am sure it'll defiantly work

0
votes

It looks to me like you added all the subviews to the same nib (or xib) file. Hence there is no nib with name "SubView1".

To solve this either add an individual xib file for every view:

File → New → File... → User Interface → View

and name those files accordingly or keep references to your views in your view controller class. You can do that by creating outlets for the views. Or you can assign a tag to each view and get a reference to that particular view with the UIView method -viewWithTag:.

However, I would recommend to use the method @Manthan suggested in his comment - if possible: Add all the subviews to your mainView in interface builder and set their hidden property to YES. Then when you want those views to appear use [yourView setHidden:NO]; in your code.

If that does not work for you I would suggest you use the first method with individual xib files.