Reputation: 1709
I have a table view that displays the cell index in a label, so the table view might look something like:
0
1
2
3
4
I want to let the user delete a cell with an animation using:
tbl.deleteRows(at: [IndexPath(row: idx, section: 0)], with: .automatic)
But the problem is, then the other cells don't update their index labels after the animation. So if for example I deleted index 1, then after the delete animation is completed, the table ends up looking like:
0
2
3
4
What's the best way to reload the table view after the delete animation, since deleteRows doesn't have a completion callback?
I'm not interested in just calling tbl.reloadData()
in place of tbl.deleteRows(...)
since I am interested in the delete animation.
Thanks
Upvotes: 2
Views: 886
Reputation: 1652
You can use the performBatchUpdates
of UITableView
and update the other rows upon completion:
tbl.performBatchUpdates({
self.tbl.deleteRows(at: [IndexPath(row: idx, section: 0)], with: .automatic)
}, completion: { (done) in
let indexPathsToUpdate = (idx...self.tbl.numberOfRows(inSection: 0)).map { IndexPath(row: $0, section: 0) }
self.tbl.reloadRows(at: indexPathsToUpdate, with: .none)
})
Or can also perform these operations with beginUpdates
and endUpdates
and the animations will happen simultaneously:
let indexPathsToUpdate = (idx+1...tbl.numberOfRows(inSection: 0)).map { IndexPath(row: $0, section: 0) }
tbl.beginUpdates()
tbl.deleteRows(at: [IndexPath(row: tbl, section: 0)], with: .automatic)
tbl.reloadSections(IndexSet(integersIn: 0...0), with: .none)
tbl.endUpdates()
Please note I used reloadRows(at: indexPathsToUpdate, with: .none)
with animation .none
as suggested, but it's up to you the way you would like them to be update, using some animation or not.
Upvotes: 2