删除带动画的行后更新 table 视图的最佳方法?
Best way to update a table view after deleting a row with animation?
我有一个 table 视图在标签中显示单元格索引,因此 table 视图可能类似于:
0
1
2
3
4
我想让用户使用以下动画删除单元格:
tbl.deleteRows(at: [IndexPath(row: idx, section: 0)], with: .automatic)
但问题是,其他单元格在动画播放后不会更新它们的索引标签。因此,例如,如果我删除了索引 1,那么在删除动画完成后,table 最终看起来像:
0
2
3
4
删除动画后重新加载table视图的最佳方法是什么,因为 deleteRows 没有完成回调?
我对只调用 tbl.reloadData()
代替 tbl.deleteRows(...)
不感兴趣,因为我对删除动画感兴趣。
谢谢
您可以使用 UITableView
的 performBatchUpdates
并在完成后更新其他行:
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: [=10=], section: 0) }
self.tbl.reloadRows(at: indexPathsToUpdate, with: .none)
})
或者也可以用 beginUpdates
和 endUpdates
执行这些操作,动画将同时发生:
let indexPathsToUpdate = (idx+1...tbl.numberOfRows(inSection: 0)).map { IndexPath(row: [=11=], section: 0) }
tbl.beginUpdates()
tbl.deleteRows(at: [IndexPath(row: tbl, section: 0)], with: .automatic)
tbl.reloadSections(IndexSet(integersIn: 0...0), with: .none)
tbl.endUpdates()
请注意,我按照建议将 reloadRows(at: indexPathsToUpdate, with: .none)
与动画 .none
结合使用,但这取决于您希望更新它们的方式,是否使用某些动画。
我有一个 table 视图在标签中显示单元格索引,因此 table 视图可能类似于:
0
1
2
3
4
我想让用户使用以下动画删除单元格:
tbl.deleteRows(at: [IndexPath(row: idx, section: 0)], with: .automatic)
但问题是,其他单元格在动画播放后不会更新它们的索引标签。因此,例如,如果我删除了索引 1,那么在删除动画完成后,table 最终看起来像:
0
2
3
4
删除动画后重新加载table视图的最佳方法是什么,因为 deleteRows 没有完成回调?
我对只调用 tbl.reloadData()
代替 tbl.deleteRows(...)
不感兴趣,因为我对删除动画感兴趣。
谢谢
您可以使用 UITableView
的 performBatchUpdates
并在完成后更新其他行:
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: [=10=], section: 0) }
self.tbl.reloadRows(at: indexPathsToUpdate, with: .none)
})
或者也可以用 beginUpdates
和 endUpdates
执行这些操作,动画将同时发生:
let indexPathsToUpdate = (idx+1...tbl.numberOfRows(inSection: 0)).map { IndexPath(row: [=11=], section: 0) }
tbl.beginUpdates()
tbl.deleteRows(at: [IndexPath(row: tbl, section: 0)], with: .automatic)
tbl.reloadSections(IndexSet(integersIn: 0...0), with: .none)
tbl.endUpdates()
请注意,我按照建议将 reloadRows(at: indexPathsToUpdate, with: .none)
与动画 .none
结合使用,但这取决于您希望更新它们的方式,是否使用某些动画。