Loading view from xib - which methods do you override


#1

Hi folks,

BNR Alumni here (2 classes so far). Trying to understand the reasons for what I’m doing and wasn’t sure if this is the right forum.

My question is about creating custom views with xib, and how to set all init Methods to properly work with it. Here is how I’ve done it, but I just don’t know why I’m doing what I’m doing. Never really got an explanation.

I typically created a custom view in xib. Set the view to the name of the customClass, not the file owner.

After that create a custom initializer and refer to it in initWithFrame. It’s not very clear if I need to add anything into initWithCoder (I know that’s called internally). What I do works, but I would really like to know the reason for what I’m doing.

Thanks for any help.

-(instancetype)initFromXib
{
    self = [[[NSBundle mainBundle] loadNibNamed:@"xibNameHere" owner:self options:nil] objectAtIndex:0];
    {
        //self.lblName.text...;
    }
    return self;
}
 
-(instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder];
    if (self)
    {
        //do I need anything here?
    }
    return self;
}
 
-(instancetype)initWithFrame:(CGRect)frame
{
   // load from xib and set frame after?
    self = [self initFromXib];
    if (self)
    {
        self.frame = frame;
    }
    return self;
}