首页 > 解决方案 > 在 UITableView 中保持时间戳标签的更新

问题描述

我有一个 UIViewController,它有一个 UITableView,它显示从实时 Firebase 数据库中获取的评论。

每次有新评论时,我都会打电话

tableView.beginUpdates()
tableView.insertRows(at: [IndexPath(row: self.liveComments.count-1, section: 0)], with: .fade)
tableView.endUpdates()

插入带有淡入淡出动画的最新评论。这工作正常。

但是,每个单元格都有一个标签,以“秒、分钟或小时前”的形式显示其发布时间。问题是当许多评论到达时,年龄标签没有得到更新,因为现有的单元格没有更新,并且在用户看来评论年龄是错误的。

我试过打电话

tableView.reloadRows(at: self.tableView.indexPathsForVisibleRows ?? [], with: .none)

在我的 tableView 更新块内,但动画都搞砸了,因为所有可见的单元格似乎都以一种奇怪的“跳跃”方式进行动画处理。

我也尝试过获取所有可见单元格,并在它们上调用一个方法来手动更新它们的时间戳标签,但是当我这样做时我会崩溃,所以我想不推荐这样做:

if let visibleCells = self.tableView.visibleCells as? [LiveCommentTableViewCell] {
    visibleCells.forEach { cell in
    cell.updateCommentAgeLabel()
}

我该如何处理?我只需要重新加载所有没有动画的可见单元格,以及最后一个带有淡入动画的单元格。谢谢!

标签: iosswiftuitableview

解决方案


我只想重新加载所有数据,只要cellForRowAt正确设置时间戳标签就可以正常工作:

// still do your nice animation
tableView.beginUpdates()
tableView.insertRows(at: [IndexPath(row: self.liveComments.count-1, section: 0)], with: .fade)
tableView.endUpdates()
// now just refresh the entire table
tableView.reloadData()

当然,假设您已经在执行此操作,或者您会遇到很多错误和崩溃,那么您将要确保numberOfItemsInSection在调用 im 之前也更新了任何集合馈送reloadData()

显然,确保编辑 UI 的代码也在主线程上。

话虽这么说,你的cell.updateCommentAgeLabel()函数看起来像什么 bc 在理论上也可以工作,除非它可能不会再次在主线程上被调用或强制转换不起作用。

也许尝试告诉系统您希望它进行布局传递:

if let visibleCells = self.tableView.visibleCells as? [LiveCommentTableViewCell] {
    visibleCells.forEach { cell in
    cell.updateCommentAgeLabel()
    cell.layoutIfNeeded() // either this
}
tableView.layoutIfNeeded() // OR this at the end, I dont expect you'll need to do both but not sure if both work

推荐阅读