UITableView Cell Reuse&旧数据

时间:2016-08-06 20:31:01

标签: ios swift uitableview

我想确认我采用的方法解决了UITableView中自定义单元格的问题,因为它滚动使得单元格不包含旧单元格的数据...

包含UITableView个自定义UITableViewCells的应用(" CustomCell")。每个CustomCell都包含一个UIStackView,其中包含一个或多个通过笔尖定制的自定义视图(" CustomView")。我重复使用CustomCell如下:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier(ReuseIdentifierCustomCell, forIndexPath: indexPath) as! CustomCell
    configureCell(cell, atIndexPath: indexPath)
    return cell
}

问题是该单元格将包含" old"细胞被重复使用的数据。要解决此问题,我将在CustomCell中覆盖prepareForReuse方法,如下所示:

override func prepareForReuse() {
    super.prepareForReuse()

    for case let view as CustomView in stackView.subviews {
        view.removeFromSuperview()
    }
}

然后在layoutSubviews中,我将子视图添加回来:

override func layoutSubviews() {
    super.layoutSubviews()

    if stackView.subviews.isEmpty {
        addCustomViewsToCell()
    }
}

到目前为止,性能似乎很好,但是如果这是一种正确的方法,或者如果我将来会遇到规模问题,那就很好奇。到目前为止,我还没有找到另一种可行的方法。

由于

1 个答案:

答案 0 :(得分:0)

您重复使用单元格的代码是正确的。一种常见的方法是通过在自定义单元格上设置变量或调用函数来在cellForRowAtIndexPath函数中配置单元格数据:

let cell = tableView.dequeueReusableCellWithIdentifier(ReuseIdentifierCustomCell, forIndexPath: indexPath) as! CustomCell
cell.data = myData[indexPath.row] // where myData is an array of type [Data]
return cell

您的单元格将负责其自己的布局以显示新数据:

var data: Data {
    didSet {
        // configure and refresh your UI here
    }
}

我怀疑您的问题与您的configureCell功能有关。如果可以,请将此代码移到单元格的逻辑中。这将更清晰,更容易理解。

就性能而言,如果您的堆栈视图中没有太多内容,您现在可能会很好,但如果它们的复杂性不断增加,您可能会看到旧设备上的帧速率下降。

相关问题