reloadData()之后,我的tableView出现问题。它始终滚动到顶部。我不知道在哪里弄乱了它,因为在保持偏移位置之前,它工作得非常好。
我正在使用自动尺寸。
var currentCount: Int {
return news.count
}
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 200
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if !fetchingMore && indexPath.row == currentCount - 1 {
beginBatchFetched()
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return tableView.estimatedRowHeight
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 200
}
private func beginBatchFetched() {
fetchingMore = true
customGetAllNews(serchKey: qKey, tags: tagsAsParameter, cameFromPullToRefresh: false)
}
private func customGetAllNews(serchKey: String?, tags: [String]? = nil,....) {
Helper.getAllNews(page: self.currentPage, key: serchKey........) { (data) in
self.fetchingMore = false
guard let nws = data?.news else {return}
self.currentPage += 1
self.news.append(contentsOf: nws)
GlobalMainQueue.async {
self.tableView.reloadData()
}
}
我还尝试了其他帖子中的一些可接受的答案,例如在重新加载之前和设置后保存表格视图的偏移量,但是它并没有按预期的那样工作,因为我仍然需要滚动一点到达到我之前的观点。
而且,我已经尝试过使用heightDictionary: [Int : CGFloat] = [:]
的方法
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
heightDictionary[indexPath.row] = cell.frame.size.height
}
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
let height = heightDictionary[indexPath.row]
return height ?? UITableViewAutomaticDimension
}
但未成功,结果相同,跳转到表格视图的顶部。
@ Mohamed,请查看下面的代码,并将其放入主队列中,而不是重新加载数据。
请检查并让我知道这是否适合您。
GlobalMainQueue.async {self.tableView.reloadData()}
UIView.setAnimationsEnabled(false)
self.tableView.beginUpdates()
self.tableView.reloadSections(IndexSet(index: 1) as IndexSet, with:
UITableViewRowAnimation.none)
self.tableView.endUpdates()