Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple UITableViewCell subclasses using same xib?

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?

like image 269
trapper Avatar asked Oct 19 '22 16:10

trapper


2 Answers

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.

like image 127
DavidA Avatar answered Nov 02 '22 14:11

DavidA


Now no way for using same xib for multiple cell.

But you can separate part of xib, which that all the cell will use.

And in each cell you will set a subview to this class subview, and now you can reuse this view for all cell.

You can see my image for this example:

First cell:

enter image description here

Second Cell: enter image description here

And subview two cell use:

enter image description here

Now you don't need duplicate xib and can reuse this part of UI.

like image 36
vien vu Avatar answered Nov 02 '22 13:11

vien vu