I'm using Storyboard and trying to reuse a View for different ViewControllers.
For that, I created a custom .xib (MyCustomView.xib
) and class (MyCustomView
) as suggested pretty much everywhere.
In my Storyboard I set the custom view to be of type MyCustomView
.
In MyCustomView.xib
, set First Responder to MyCustomView
.
In MyCustomView.m
, I added the following method:
-(id)initWithCoder:(NSCoder *)aDecoder{
if ((self = [super initWithCoder:aDecoder])){
UIView *myCustomView = [[[NSBundle mainBundle] loadNibNamed:@"MyCustomView" owner:self options:nil] objectAtIndex:0];
[self addSubview: myCustomView];
}
return self;
}
Problem is, [self addSubview: myCustomView]
adds a new MyCustomView
to existing MyCustomView
, so the view is added twice.
How can I get rid of one of the two?
EDIT
My question is not really clear, so I thought some screen caps would help.
Here is my Storyboard with a custom view. Custom class is set to MyCustomView
.
(I also added a grey background and a label for testing purpose only)
Now, in MyCustomView.xib
, I set File's owner to be of Class MyCustomView
:
And add outlets for title Label and imageView:
With the initWithCoder method as written above, this works fine, except when I debug I can see this:
So
self
is of course of type MyCustomView
, as chosen in the Storyboard, but it contains 2 subviews :
- First is the test label from my storyboard
- Second is the view from
MyCustomView.xib
, itself containing a Label and image view. That's this view I want to get rid of.