gpt4 book ai didi

ios - 重新加载后保持单元格在 UITableView 中的位置

转载 作者:行者123 更新时间:2023-11-28 09:35:50 25 4
gpt4 key购买 nike

我每隔几分钟刷新一次我的 UITable,以防万一有新数据,它们应该添加到表的开头而不是重新加载。

var j = 0
let n = store?.news?.count
while(j < n!){
self.news?.insert((store?.news?[j])!, at: j)
j = j + 1
}

在第一个位置保存数据没有问题。问题是我无法在每次重新加载后保持单元格位置向上移动(添加的记录数),我尝试了多种功能但显然它只适用于在表末尾添加数据的情况。

let contentOffset = self.tableV.contentOffset
self.tableV.reloadData()
self.tableV.contentOffset = contentOffset

我也厌倦了保存单元格位置并将输入数据的计数添加到其中,但这种添加不起作用。有没有办法将输入数据的数量添加到 indexPath.row 中?

最佳答案

实际上它发生是因为它重新计算了 UITableViewAutomaticDimension 高度

您可以通过存储您的单元格高度并使用它在estimatedHeightForRowAt中为您的单元格分配来解决这个问题。
在后台,它会将您的确切 cell's height 分配给 estimatedHeightForRowAt。因此重新计算不会影响您的表格 View 。

实现如下。

// declare dictionary variable for storing heights of cells
var cellHeightsDictionary: [IndexPath: CGFloat] = [:]

然后使用 tableview 的方法 willDisplay 在字典变量中存储单元格的高度,并在 estimatedHeightForRowAt 中分别分配这些单元格的高度>

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
self.cellHeightsDictionary[indexPath] = cell.frame.size.height
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
if let height = self.cellHeightsDictionary[indexPath]{
return height
}
return UITableViewAutomaticDimension
}

就是这样。你完成了。

关于ios - 重新加载后保持单元格在 UITableView 中的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43182299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com