简体   繁体   English

滚动时的UITableView改组

[英]UITableView shuffling when scrolling

I have a UITableView set up that works almost correctly, but if you scroll all the way up or down rather quickly, it shuffles the cells out of order. 我有一个几乎可以正常工作的UITableView设置,但是如果您相当快地上下滚动,它将使单元格混乱。 I set the label to reflect the index path and even when it starts out 我设置标签以反映索引路径,即使它开始时也是如此

[0,0] [0,1] [0,2] [0,3] [0,4] [0,5] [0,6] [0,0] [0,1] [0,2] [0,3] [0,4] [0,5] [0,6]

After a quick few swipes up and down, the cells look like this 上下快速滑动几下后,单元格看起来像这样

[0,1] [0,6] [0,2] [0,3] [0,4] [0,5] [0,0] [0,1] [0,1] [0,6] [0,2] [0,3] [0,4] [0,5] [0,0] [0,1]

My code is similar to the following 我的代码类似于以下内容

import UIKit

class TableViewController : UITableViewController {

    var dates: [Date]?

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dates?.count ?? 0
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: tableViewCell.storyboardID, for: indexPath) as?  tableViewCell else { fatalError() }

        let date = dates?[indexPath.row]
        cell.date = date
        cell.delegate = self
        cell.cellIndex = indexPath

        return cell
    }
}

From Apple docs on UITableView 来自AppleTables on UITableView

When the table view asks the data source to configure a cell object for display, the data source can access the queued object by sending a dequeueReusableCellWithIdentifier: message to the table view, passing in a reuse identifier. 当表视图要求数据源配置要显示的单元格对象时,数据源可以通过向表视图发送dequeueReusableCellWithIdentifier:消息并传递重用标识符来访问排队的对象。 The data source sets the content of the cell and any special properties before returning it. 数据源在返回之前设置单元格的内容和任何特殊属性。 This reuse of cell objects is a performance enhancement because it eliminates the overhead of cell creation. 单元对象的这种重用是性能增强,因为它消除了单元创建的开销。

So in this case, you are storing the value of indexPath in the cell propeties, "cellIndex", which is reusable by other cells. 因此,在这种情况下,您将indexPath的值存储在单元格indexPath “ cellIndex”中,其他单元格可以重复使用该indexPath Therefore, it will randomly show the value based on previously assigned in queue. 因此,它将根据队列中先前分配的值随机显示该值。

In order to encounter this, you can either store the value to array variable in viewController, so every time the datasource want to re-create the cells, it will get from the array consistently. 为了解决这个问题,您可以将值存储到viewController中的数组变量中,因此,每次数据源想要重新创建单元格时,它将始终从数组中获取数据。

Secondly, you can directly assign the indexPath to the cell ui element such as UILabel. 其次,您可以将indexPath直接分配给单元ui元素(如UILabel)。

cell.titleLabel.text = "\(indexPath)"

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

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