我创建了一个小项目来展示它可以完成的一种方式。 Git it enter link description here
它是如何工作的?
的属性声明,其中最新的点击细胞将被存储:
var lastSelectedCells = [IndexPath]()
因为我们希望有在该阵列的顶部的最新单击的单元格,这里就是我们做的方法“DidSelectCellAtRowIndexPath” :
lastSelectedCells.insert(indexPath, at: 0)
我们也想更新已被点击(含现任在内)之前的细胞,因此,右后上方,我们执行:
tableView.reloadRows(at: lastSelectedCells, with: .automatic)
逻辑的其余部分是在“的cellForRowAtIndexPath”方法,如下所示(与项目一点简化):
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "NiceCell") as! MyBeautifulCell
if let index = lastSelectedCells.index(of: indexPath) {
cell.centeredLabel?.text = "Cell tapped \(index) times ago!"
} else {
cell.centeredLabel?.text = "Uhmpf, this cell was never tapped!"
}
return cell
}
即:如果当前indexPath是阵列中,我们设置将单元格的文本作为它的索引,否则我们设置一些脾气暴躁的文本。
我不知道你的整个项目,但这应该足以让你实现你想做的事情。
既然你说:我需要在前面的细胞清除数据...... 你可以如下改变方法:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "NiceCell") as? MyBeautifulCell else {
fatalError("Table Configuration Error!")
}
if let index = lastSelectedCells.index(of: indexPath) {
switch index {
case 0:
cell.centeredLabel?.text = "Cell tapped"
default:
cell.centeredLabel?.text = "CLEARED"
}
} else {
cell.centeredLabel?.text = "Uhmpf, this cell was never tapped!"
}
return cell
}
如果你走这条路,在reloadRows实现可以重新加载只有第二最后一行,但这将是一个优化。
您不需要访问任一单元格。更新您的表的数据源使用的数据模型,然后通知表视图重新加载受影响的索引路径。 – rmaddy
*不在视图中的单元不存在。 – vadian