为什么在单元格不可见时调用cellForRowAtIndexPath?

时间:2016-01-13 22:06:46

标签: ios swift uitableview

UITableViewController坐在Container内,坐在另一个UIViewController内。我在故事板中构建它。 Here is a snap.有问题的UITableViewController位于右侧,称为LayerTableViewController

出于某种原因,正在为当前不可见的单元格调用此UITableView的cellForRowAtIndexPath方法。我通过将方法更改为以下方法对此进行了测试:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("layerCell", forIndexPath: indexPath) as! LayerTableViewCell

    // Configure the cell...

    cell.layerCircleView.layer.cornerRadius = cell.layerCircleView.layer.bounds.width / 2
    let label = UILabel(frame: CGRect(x: cell.layerCircleView.frame.midX - 10, y: cell.layerCircleView.frame.midY - 10, width: 20, height: 20))
    label.text = String(indexPath.row)
    cell.layerCircleView.addSubview(label)
    print("indexPath.row: \(indexPath.row)")

    return cell
}

此代码产生以下奇怪的结果。在控制台中,偶尔会无序打印数字。不在可见屏幕附近的单元格将indexPath.row传递给此方法。此外,我正在制作的UILabels全部呈现在彼此之上。 Here is a combined image of the simulator and terminal output. 正如您所看到的,当indexPath.row: 0位于二十世纪二十年代中期时,有一条随机行显示indexPath.row

总而言之,为什么要求cellForRowAtIndexPath使用indexPath.row当前不可见,以及为什么这些数字会相互重叠?

1 个答案:

答案 0 :(得分:0)

所以我仍然不确定为什么有cellForRowAtIndexPath随机调用不可见的细胞,但这似乎不是一个大问题。我认为这和覆盖的渲染是相关的,但它们不是。

重叠渲染的问题是所有UILabels都被添加到UITableViewCell的子视图中,即cell.layerCircleView。因此,正如我发现的那样,当重用单元格时,对layerCircleView的引用也是如此。因此,我必须做的就是在离开屏幕时清理视图:

override func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    let cell = cell as! LayerTableViewCell
    for subview in cell.layerCircleView.subviews {
        subview.removeFromSuperview()
    }
}
相关问题