我有一个 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/