我有 3 个自定义单元格要显示在一个 50 行的表格 View 中。 我找到了满足我需要的引用资料 Multiple Custom Cells dynamically loaded into a single tableview
为单元格创建对象似乎变得很复杂。 根据我的需要,3 个单元执行相同的功能,但 View 不同,
我们可以使用工厂模式来构建单元格吗?
这种模式有实现吗?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// I would like to create object some like this
CustomCell *cell = factory.getCell("customCell1", tableView);
}
我有自定义单元格的类图。
最佳答案
- (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;
}
//你的工厂类。
- (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;
}
关于ios - 使用工厂模式在同一个表中加载不同的自定义单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24968630/