在表中处理UITableViewCell的多个子类

时间:2016-04-18 03:45:10

标签: ios swift uitableview

我在详细视图控制器中构建UITableView。该表视图的某些方面包括:

  • 在Interface Builder中使用标识符/子类定义多个单元格样式;例如,PhotoCellInfoCell,两者都扩展为UITableViewCell
  • 动态生成单元格。如果详细视图控制器中缺少某些值,则不会显示这些单元格。
  • UITableViewCell的每个子类中,我创建了一个static createCell()方法,该方法使用tableView.dequeueReusableCellWithIdentifier返回已初始化的已填充单元格。

问题

  1. 在此方案中构建表格视图的最佳做法是什么?
  2. 在下面的方法中,在数据源委托方法以外的方法中使用dequeueReusableCellWithIdentifier是否可接受(甚至有用)?
  3. 当前方法

    我采用的方法是定义包含单元格数组的source属性。我不确定这是否是处理它的最佳方式。

    PlaceViewController + UITableViewDataSource.swift

    extension PlaceViewController: UITableViewDataSource {
    
        var source: [UITableViewCell] {
            get {
                var cells = [UITableViewCell]()
    
                if let cell = SummaryCell.createCell(tableView, text: place?.generalInfo) {
                    cells.append(cell)
                }
                // ^^ repeat above for each cell in table           
    
                return cells
            }
        }
    
        func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return source.count
        }
    
        func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
            return source[indexPath.row]
        }
    
    }
    

    SummaryCell.swift

    class SummaryCell : UITableViewCell {
    
        @IBOutlet var summaryLabel: UILabel!
    
        static func createCell(tableView: UITableView, text: String?) -> SummaryCell? {
            if let text = text {
                let cell = tableView.dequeueReusableCellWithIdentifier("SummaryCell") as! SummaryCell
                cell.summaryLabel.text = text
                return cell
            }
            return nil
        }
    
    }
    

1 个答案:

答案 0 :(得分:0)

如果您正在为表使用不同的单元格,也可以进行条件检查或在特定索引中切换所需的单元格类型,然后尝试使用已创建的单元格进行双击 - 如果不初始化新的一个。

另外,看看你的代码,每当调用cellForRowAtIndexPath时,你就会创建一个新的单元格数组,这是不好的。

相关问题