iosawakefromnib

awakeFromNib vs. initWithFrame for custome UITableViewCell


I need to make a custom UITableViewCell, so I created a subclass with associated nib file.

I need to add some subviews to it. Does awakeFromNib replace initWithFrame when using a nib file? I am using [[NSBundle mainBundle] loadNibNamed: in my cellForRowAtIndexPath method.

Do I use initWithFrame like so?

- (id)initWithFrame:(CGRect)frame
{
    if ((self = [super initWithFrame:frame]))
    {
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 100, 320)]

        [self addSubview:self.horizontalTableView];
    }

    return self;
}

Or do I do it in awakeFromNib like so

- (void)awakeFromNib
{
   self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 100, 320)]

            [self addSubview:self.horizontalTableView];
}

Solution

  • When you are creating a Xib, initWithFrame will not be used. However, initWithCoder will be used. So, you can do extra instantiation in there. However, there is nothing wrong with initializing other controls in awakeFromNib either.

    Edit: in response to your first comment below, check out this related question:

    Should I be using awakeFromNib or initWithCoder here?