繁体   English   中英

处理表中的UITableViewCell的多个子类

[英]Handling multiple subclasses of UITableViewCell within a table

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

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

问题

  1. 在这种情况下构建表格视图的最佳实践是什么?
  2. 在下面的方法中,在数据源委托方法以外的方法中使用dequeueReusableCellWithIdentifier是否可以接受(甚至有用)?

当前方法

我采用的方法是定义一个包含单元格数组的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
    }

}

如果您为表使用不同的单元格,则不妨进行条件检查或切换特定索引中所需的单元格类型,然后尝试确定是否已创建了这种类型的单元格-如果未初始化新的单元格。

另外,查看您的代码,每当调用cellForRowAtIndexPath的调用时,您都将创建一个新的单元格数组,这不好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM