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.
- (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;
}