ios - 如何在快速重新加载数据后使表格视图显示特定行?
问题描述
我正在尝试在表格视图中实现分页。所以从服务器获取数据时,我想每个请求获取 10 个数据。
所以用户第一次打开视图时,它会获取 10 条数据,当用户滚动到第 10 行后,它会发送请求获取第 11 到第 20 条数据。
但是在获取第 11-20 个数据并重新加载表格视图后,表格视图似乎向下拖动并显示最后一行(即第 20 行)。
我想在第 10 行之后 --> 获取数据 --> 显示表格视图的第 11 行
所以它将提供流畅的滚动和良好的用户体验
这是我使用的简化代码。提前致谢
let numberOfDocumentsPerQuery = 5
var fetchingMore = false
var recommendedEventList = [EventKM]()
var lastDocumentFromQuery : QueryDocumentSnapshot?
extension HomeVC : UITableViewDelegate, UITableViewDataSource {
//MARK: - Table View Methods
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return recommendedEventList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCell", for: indexPath) as! HomeCell
cell.eventData = recommendedEventList[indexPath.row]
return cell
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
// to fetch more events if it comes to the bottom of table view
let currentOffset = scrollView.contentOffset.y
let maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height
if maximumOffset - currentOffset <= 10.0 {
if !fetchingMore {
getRecommendedEvents()
}
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "toEventDetailVC", sender: nil)
}
}
func getRecommendedEventsFromBeginning() {
EventKM.observeRecommendedEvents (
selectedCity: selectedCity,
limit: numberOfDocumentsPerQuery) { (recommendedList, listener, lastDocument) in
if let events = recommendedList {
self.recommendedEventList = events
self.tableView.reloadData()
self.lastDocumentFromQuery = lastDocument
self.recommendedListener = listener
self.fetchingMore = false
} else {
self.fetchingMore = true // to stop fetching data
}
}
}
解决方案
您可以有一个属性来记录滚动到的行。
var rowForScroll = 1
每次加载数据时,添加rowForScroll
rowForScroll = rowForScroll + 10
let ip = NSIndexPath(forRow: rowForScroll, inSection: 0)
self.tableView.scrollToRowAtIndexPath(ip, atScrollPosition: .bottom, animated: true)
推荐阅读
- mongodb - 参考其当前值更新所有文档的 mongodb 中的特定字段
- python - Python多处理循环,奇怪的行为
- vue.js - Vue.js 中 v-if 和 v-for 的过滤问题
- arrays - 在多列条件下过滤 numpy 数组
- python - Python数独求解器
- react-native - 为什么我的代码不起作用,并且在 react-native 中也没有显示任何错误
- java - 如何在android中将项目添加到recyclerView
- python - 为什么 Conda 在我的环境之外使用 python 包?
- regex - 基数 m 的 NFA 不能被 n 整除
- tensorflow - 急切执行与多处理不兼容