【问题标题】:Loading different custom cells in the same table using factory pattern使用工厂模式在同一个表中加载不同的自定义单元格
【发布时间】:2014-07-26 07:23:48
【问题描述】:

我有 3 个自定义单元格显示在一个 50 行的表格视图中。 我找到了满足我需要的参考 Multiple Custom Cells dynamically loaded into a single tableview

为单元格创建对象似乎变得很复杂。 根据我的需要,3 个单元具有相同的功能,但视图不同,

我们可以使用工厂模式来构建单元吗?

这种模式有实现吗?

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

}

我有自定义单元格的类图。

【问题讨论】:

  • 你在使用故事板吗?
  • 不,我没有使用故事板,我使用 xib 创建自定义单元格。
  • 你看到我编辑的答案了吗?

标签: ios factory-pattern custom-cell


【解决方案1】:
- (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;
}

【讨论】:

  • 感谢您的回复,上面的代码适用于通过标识符使单元格出列,但同样我想创建一个工厂,从 Xib 创建一个新单元格并将这些单元格出列,对吗?跨度>
【解决方案2】:

工厂方法不合适,因为它不允许您出列。

注册每个自定义类以便在您的表格视图中重复使用(viewDidLoad 是这样做的好地方):

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

cellForRowAtIndexPath,确定你想要的类型,然后出队:

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

如果可能,将创建一个新单元格,或者从池中返回一个新单元格。

【讨论】:

  • 感谢您的回复,如果我将 tableView 引用发送给工厂,那么工厂可以将单元格出列,CustomCell *cell = factory.getCell("customCell1", tableView);
  • @satyanarayana 工厂方法根本不是正确的方法。您已经从表格视图中获得了可重用的队列行为。
  • @duci9y 是绝对正确的。表格视图将完成您的“工厂”的工作,并负责重用。不要与框架抗争。
猜你喜欢
  • 1970-01-01
  • 2013-07-25
  • 1970-01-01
  • 2017-01-04
  • 1970-01-01
  • 2012-08-25
  • 1970-01-01
  • 1970-01-01
  • 2012-12-06
相关资源
最近更新 更多