UITableView with two custom cells (multiple identifiers)

* I’ve renamed some of your NIB/Class names for a better understanding. *

First, you should register each cells’ NIB:

- (void)viewDidLoad{
    [super viewDidLoad];

    static NSString *CellIdentifier1 = @"ContentCell";
    static NSString *CellIdentifier2 = @"SpaceCell";

    UINib *nib = [UINib nibWithNibName:@"CellViewNIBName" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:CellIdentifier1];

    nib = [UINib nibWithNibName:@"CellSpaceNIBName" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:CellIdentifier2];

    self.contentView.hidden = YES;
    [self loadData];
}

Because you have the NIBs registered, dequeueReusableCellWithIdentifier: will always return a cell:

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath      *)indexPath
{
    static NSString *CellIdentifier1 = @"ContentCell";
    static NSString *CellIdentifier2 = @"SpaceCell";

    // Space Cell
    if (indexPath.row % 2 == 1) {
        CellSpace *cell = (CellSpace *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
        return cell;
    }

    // Content cell
    else {
        CellView *cell = (CellView *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
        // Configure cell
        return cell;
    }
}

Last, but not least, make sure to implement the following delegate method:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Space cell's height
    if (indexPath.row % 2 == 1) {
        return 20.0f;
    }

    // Content cell's height
    else {
        return 80.0f;
    }
}

Leave a Comment