Ios 在UITableView中保持时间戳标签的更新

Ios 在UITableView中保持时间戳标签的更新,ios,swift,uitableview,Ios,Swift,Uitableview,我有一个UIViewController,它有一个UITableView,它显示从live Firebase数据库获取的注释 每次有新评论出现,我都会打电话给你 tableView.beginUpdates() tableView.insertRows(at: [IndexPath(row: self.liveComments.count-1, section: 0)], with: .fade) tableView.endUpdates() 插入带有淡入淡出动画的最新注释。这个很好用 但是,

我有一个UIViewController,它有一个UITableView,它显示从live 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()
}

我怎样才能做到这一点?我只需要重新加载所有没有动画的可见单元格,以及最后一个带有淡入动画的单元格。谢谢大家!

我只需重新加载所有数据,只要
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()
当然,在调用
reloadData()
im之前,您需要确保为
numberofitemsinssection
提供信息的任何集合都会被更新,我假设您也已经这样做了,否则会遇到很多bug和崩溃

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

也就是说,你的
cell.updateCommentAgeLabel()
函数看起来像bc,在理论上也可以工作,除非它可能不再在主线程上被调用,或者cast不工作

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

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

你在endUpdates之后调用reload吗?我在endUpdated之前以及它自己的begin/end updated块中都尝试过,但都没有成功。我应该在哪里给reloadRows打电话?Gadu,谢谢你的回答!这实际上是我一直在做的事情,直到今天,我的客户有一个不同的要求:他们需要一个动画在单元格中播放,每当重载数据触发时,动画从一开始就开始。有没有办法只更新我需要的单元格的一部分(时间标签)而不是整个单元格?嗯,我不确定当你尝试在可见单元格上调用“updateTimeLabel”时会发生什么崩溃,但这确实让我觉得理论上应该可以用