Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading different custom cells in the same table using factory pattern

I have 3 custom cells to be displayed in one tableview of 50 rows. I found a reference which satisfies my need at Multiple Custom Cells dynamically loaded into a single tableview

It seems it gets complicated to create objects for cells. As per my need 3 cells do same functionality but views are different,

can we use a factory pattern to build cells?

Is there any implementation for this kind of pattern?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
      // I would like to create object some like this
      CustomCell *cell = factory.getCell("customCell1", tableView);

}

I have the class diagram for custom cells. enter image description here

like image 854
satyanarayana Avatar asked Jan 18 '26 21:01

satyanarayana


2 Answers

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell<CustomCellProtocol> *cell = [factory getCellForIndexPath:indexPath tableView:tableView];

    // Getting data for the current row from your datasource
    id data = self.tableData[indexPath.row]; 
    [cell setData:data];

    return cell;
}

// Your Factory class.

- (UITableViewCell<CustomCellProtocol> *)getCellForIndexPath:(NSIndexPath *)indexPath tableView:(UITableView *)tableView
{
    UITableViewCell<CustomCellProtocol> *cell;
    NSString *cellNibName;
    if (condition1) {
        cellNibName = @"CustomCell1"; //Name of nib for 1st cell
    } else if (condition2) {
        cellNibName = @"CustomCell2"; //Name of nib for 2nd cell
    } else {
        cellNibName = @"CustomCell3"; //Name of nib for 3th cell
    }

    cell = [tableView dequeueReusableCellWithIdentifier:cellNibName];

    if (!cell) {
        UINib *cellNib = [UINib nibWithNibName:cellNibName bundle:nil];
        [tableView registerNib:cellNib forCellReuseIdentifier:cellNibName];
        cell = [tableView dequeueReusableCellWithIdentifier:cellNibName];
    }

    return cell;
}
like image 181
arturdev Avatar answered Jan 20 '26 13:01

arturdev


A factory method isn't appropriate because it doesn't allow you to dequeue.

Register each custom class for reuse with your table view (viewDidLoad is a good place to do this):

[self.tableView registerClass:[CustomCell1 class] forReuseIdentifier:@"customCell1"];
// Repeat for the other cell classes, using a different identifier for each class

In cellForRowAtIndexPath, work out which type you want, then dequeue:

CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
[cell setData:data]; // all subclasses can do this

A new cell will be made, or returned from the pool if possible.

like image 33
jrturton Avatar answered Jan 20 '26 14:01

jrturton