Reputation: 571
I've a table view where cells can be inserted and deleted. For insertion of cells, I use the following code:
tableView.beginUpdates()
tableView.insertRows(at: [IndexPath(row: cellCount-2, section: 0)], with: .automatic)
tableView.endUpdates()
For deleting cells, I use the following code:
tableView.beginUpdates()
tableView.deleteRows(at: [indexPath], with: .automatic)
tableView.endUpdates()
Attaching the gif of the issue I face. On deleting a cell and inserting a new one, the contents of the cell gets populated in the new cell. Can someone help me sort this issue?
Upvotes: 1
Views: 632
Reputation: 2073
If you are using the standard UITableViewCell
remember to reset the content inside the UITableViewDelegate function cellForRowAtIndexPath
since the dequeueReusableCell
will recycle an already initialized cell (that has to be brought to its original state)
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "aCellIdentifier", for: indexPath)!
...
cell.title.text = ""
cell.description.text = ""
}
A typical approach is however to subclass UITableViewCell
and implement prepareForReuse
method (which is called automatically before the cell being reused), where you will eventually reset all labels, images, subviews to the initial state
override func prepareForReuse() {
super.prepareForReuse()
self.labelScore.text = ""
self.labelDate.text = ""
}
Upvotes: 4