首页 > 解决方案 > 如何在快速重新加载数据后使表格视图显示特定行?

问题描述

我正在尝试在表格视图中实现分页。所以从服务器获取数据时,我想每个请求获取 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
            }


        }

    }

标签: iosswiftuitableview

解决方案


您可以有一个属性来记录滚动到的行。
var rowForScroll = 1

每次加载数据时,添加rowForScroll

rowForScroll = rowForScroll + 10
let ip = NSIndexPath(forRow: rowForScroll, inSection: 0)
self.tableView.scrollToRowAtIndexPath(ip, atScrollPosition: .bottom, animated: true)

推荐阅读