ios - 延迟出列可重复使用的单元格

标签 ios swift uitableview grand-central-dispatch

我有一个 tableView,我使用 DispatchQueue 方法延迟插入 20 行。前 10 行看起来很好。当 Xcode 开始使可重用行出列时,问题从第 11 个开始。在模拟器中,它看起来几乎同时开始插入 2 行(第 11+12,然后第 13+14)。

我想知道为什么会这样。 DispatchQueue 和 tableView.dequeueReusableCell 方法是否冲突?如果是,如何正确组织事情?

var numberOfCells = 0

//My TableView
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "TextCell")! as UITableViewCell
    return cell
}

//Function that inserts rows
func updateTableView(nextPassageID: Int) {
    for i in 0...numberOfCells - 1 {
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(i)) {
            self.numberOfCells += 1
            let indexPath = IndexPath(row: i, section: 0)
            self.tableView.insertRows(at: [indexPath], with: .fade)
            }
    }
}

最佳答案

我认为在您的用例中使用 Timer 是更好的解决方案:

private var cellCount = 0

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return cellCount
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.textLabel?.text = "Cell \(indexPath.row)"
    return cell
}

func addCells(count: Int) {
    guard count > 0 else { return }

    var alreadyAdded = 0
    Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] t in
        guard let self = self else {
            t.invalidate()
            return
        }

        self.cellCount += 1

        let indexPath = IndexPath(row: self.cellCount - 1, section: 0)
        self.tableView.insertRows(at: [indexPath], with: .fade)

        alreadyAdded += 1
        if alreadyAdded == count {
            t.invalidate()
        }
    }
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    addCells(count: 20)
}

关于ios - 延迟出列可重复使用的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58161944/

相关文章:

ios - CGContext 引用为 UIImage

ios - 在 swift 中开设一个类中的类的成本是多少?

ios - 解决快速错误: Cannot specialize a non-generic definition

ios - 在 iOS/Swift 中以编程方式设置 View 后 RevealViewController 不工作

ios - 在tableView中添加日期作为节标题

ios - UITableViewCell Swift 中的自定义 View

ios - 编辑表格时的 UITableViewCell 行操作

ios - 从 Cocoapods 迁移到 Swift Package Manager 但导入模块失败

ios - 如何使用 Swift 将 "Done"按钮添加到 iOS 中的小键盘?

iphone - UITableviewcell 内容更新反射(reflect)到其他单元格