Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to call [self addSubView]?

I have a custom view to which I need to add a couple of subviews programmatically. Which is the best place to create and add these subviews? Apple docs say:

If your view class manages one or more integral subviews, do the following: Create those subviews during your view’s initialization sequence.

This is a bit unclear to me. Should I handle that in initWithFrame, initWithCoder or somewhere else?

Note that I'm not talking about controllers here, this is a View that needs to initialize itself.

like image 252
georg Avatar asked Jan 04 '12 09:01

georg


1 Answers

initWithFrame is the method you call to create a UIView programmatically, while initWithCoder is called when a UIView is instanciated from a XIB.

So it all depends on how you're going to create your containing view. A way to cover all cases :

- (id) initWithFrame:(CGRect)frame
{
    if ((self = [super initWithFrame:frame])){
         [self setUpSubViews];
    }
    return self;
}

- (id) initWithCoder:(NSCoder*)aDecoder 
{
    if ((self = [super initWithCoder:aDecoder])){
         [self setUpSubViews];//same setupv for both Methods
    }
    return self;
}

- (void) setUpSubViews
{
     //here create your subviews hierarchy
}
like image 141
Vinzzz Avatar answered Oct 05 '22 18:10

Vinzzz