ios - 使用工厂模式在同一个表中加载不同的自定义单元格

标签 ios factory-pattern custom-cell

我有 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);

}

我有自定义单元格的类图。 enter image description here

最佳答案

- (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/

相关文章:

ios - 如果用户拥有没有 watch 扩展的 Apple Watch,如何在 iOS 应用程序中进行跟踪?

ios - 远程 mp3 文件需要花费大量时间在 swift ios 中播放

ios - 是否有必要在 IOS 应用程序中显示 Google Analytics 隐私政策

c# - 为什么我不能通过 Type.GetType() 找到我在 app.config 中引用的插件实例的类型?

ios - UITableView 自定义单元格中单元格重用的问题

ios - 持续集成对于iOS开发是否可行?

c# - 关于工厂设计架构的问题

c# - 使用泛型但没有基类的工厂类

uitableview - UITableViewCells 的不同 - 重复模式

ios - 在自定义单元格内动态添加标签