Several UITableViewCell subclasses using the same xib?

advertisements

How can I share one xib among multiple UITableViewCell subclasses?

They all have the same view interface so I don't want to have to duplicate the same xib multiple times just to change the cell class.

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self.tableView registerNib:[UINib nibWithNibName:@"BaseCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"BaseCell"];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BaseCell *baseCell = [tableView dequeueReusableCellWithIdentifier:@"BaseCell" forIndexPath:indexPath];

    ...

What I need here instead is an instance of my ChildCell - which is a subclass of BaseCell. Any ideas?


Use composition rather than inheritance. Keep the 1-1 relationship between your BaseCell class and it's cell in the nib, add a property for an implementation object which you create and add to the cell object after you dequeue it.