Multiple subclasses of UITableViewCell using the same xib?

How can I share one xib between multiple subclasses of UITableViewCell ?

They all have the same view interface, so I don’t want to duplicate the same xib several times 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]; ... 

Instead, I need an instance of my ChildCell - which is a subclass of BaseCell . Any ideas?

+5
source share
2 answers

Use composition, not inheritance. Keep the ratio 1-1 between your BaseCell class and its cell in nib, add a property for the implementation object that you create and add to the cell object after it is deleted.

+1
source

Now there is no way to use the same xib for multiple cells.

But you can separate the xib part that the whole cell will use.

And in each cell you set a subview for this subview class, and now you can reuse this view for the whole cell.

You can see my image for this example:

First cell:

enter image description here

Second cell: enter image description here

And a subquery of two cell usage:

enter image description here

Now you do not need a duplicate xib and it can reuse this part of the user interface.

+1
source

Source: https://habr.com/ru/post/1241976/


All Articles