custom tableviewCells for UITableView created programatically in storyboard

cocoa-touch, ios, uitableview

Solution

I'd avoid putting layout and building of your cell into `cellForRowAtIndexPath`.

To create a custom cell programatically you should first create a `UITableViewCell` subclass.

Add to it the `labels`, `imageViews`, etc... Add the as subViews of the `cell.contentView`.

PROGRAMATICALLY

i.e.

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        _label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 21)];
        [self.contentView addSubview:_label];
    }
    return self;
}

If you want to do layout stuff of the cell then in the `MyCell` class you can do...

- (void)layoutSubViews
{
    [super layoutSubviews];
    // layout stuff relative to the size of the cell.
}

Then in the `tableViewController` you need to register the cell class...

In `viewDidLoad`...

[self.tableView registerClass:[MyCell class] forCellReuseIdentifier:@"MyCellIdentifier"];

WITH INTERFACE BUILDER

Still create the custom subclass but also create a xib file of the same name. Then in your xib file you can hook up the outlets instead of having to create them in the init of the cell. (If you do it this way then the init will not be called anyway).

The only other change you need is that in `viewDidLoad` you need to register the nib for the cell not the class.

Like this...

UINib *cellNib = [UINib nibWithNibName:@"MyCell" bundle:nil];
[self.tableView registerNib:cellNib forCellReuseIdentifier:@"MyCellIdentifier"];

Then everything else works the same.

USING THE CELL

To use the cell that you have created the subclass for...

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCellIdentifier"];

    [self configureCustomCell:(MyCell*)cell atIndexPath:indexPath];

    return cell;
}

- (void)configureCustomCell:(MyCell*)cell atIndexPath:(NSIndexPath *)indexPath
{
    // do all you logic of getting any info from arrays etc in here.

    cell.label.text = @"Blah".
}

SUMMARY

Doing it this way means that your tableviewcontroller is only interested in putting stuff into the cells. If you put all your logic for building your cells as well everything just gets really messy.

It also means you don't have to deal with loads of different tags to save and retrieve different UI elements.

Problem

In my app I am using storyboard. But I created a `UITableView` programmatically instead of dragging from Object Library. And now I want to customize the cells of that programmatically created `UITableView`. Can anyone help me by providing an example of creating a `UITableViewCell` programmatically in storyboard?

Original source