Search code examples
ioscustom-cell

A smart way to configure custom cells on table load-up?


I've got a table view with about 5 different custom cells, which are designed in the storyboard.

Each of these cells has its own dedicated subclass of UITableViewCell.

In cellForRowAtIndexPath, I dequeue the cells:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:self.cellArray[indexPath.row] forIndexPath:indexPath];

The problem now is, I want to call configureCell for each of these cells. Each of my custom cell classes has this method declared and implemented, but the problem is that XCode throws an alert unless I first cast these cells to their respective classes, because as far as XCode is concerned, these cells are UITableViewCell cells.

Individually casting each cell type is doable, but verbose, with lots of if and else if lines. Is there a smarter way to do this, perhaps using a protocol declaring a method configureCell?


Solution

  • Exactly, with a protocol. I think it's more flexible than subclassing, but it depends on the semantics of each cell class, and you can always mix and match both approaches.

    @protocol CellX
    - (void)configure:(id)data;
    @end
    
    @interface CellA : UITableViewCell <CellX>
    @end
    
    @interface CellB : UITableViewCell <CellX>
    
    @end
    

    In the cell creation method:

    NSString *identifier = /* pick one for the indexPath and whatnot */
    id<CellX> cell = (id<CellX>)[tableView dequeueReusableCellWithIdentifier:<#identifier#>
                                                                forIndexPath:indexPath];
    
    /* cell can be of class CellA or CellB depending on the selected identifier */
    [cell configure:<#data#>];
    

    In addition to the configuration method you can add to the protocol any property that is shared across cells (like kind, status, etc. whatever you use to deal with the cells).