列表的一半将在开始时加载,当到达列表的末尾时,另一半将添加到表视图内的下方

发布于 2025-01-16 04:24:35 字数 94 浏览 2 评论 0原文

我有一个 tableView 和 json 数据。我希望 tableview 加载一半的 json 数据。当表视图滚动到前半部分结束时,另一半将被加载。有人知道我该怎么做吗?

I have a tableView and json data.I want tableview load half in json data. When table view scroll comes to the end of the first half , the other half will be load.Can anyone know how I can ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

甜中书 2025-01-23 04:24:35

我相信您必须在 scrollViewDidScroll 的帮助下进行一些 pagination 类型的处理,以观察何时到达 tableview 的末尾以加载下一批

首先设置一些初始变量来帮助您跟踪分页过程。

var pageStart = 0
var pageSize = 15

// scrollViewDidScroll will be called several times
// so we need to be able to block the loading process
var isLoadingItems = false

// Array of 50 values which you get from the API
// For example your JSON data
var totalNumberOfItems = (0...49).reduce([Int]())
{ (result, number) in
    
    var array = result
    array.append(number)
    return array
}

// This will periodically be filled with items from totalNumberOfItems
var itemsToLoad: [Int] = []

我创建了这个加载函数,它有助于批量添加项目并适当地重新加载表格视图

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(true)
    loadItems()
}

private func loadItems(withDelay delay: Double = 0) {
    
    // Check that there are items to load
    if pageStart < totalNumberOfItems.count, !isLoadingItems {
        
        isLoadingItems = true
        
        // The delay and dispatch queue is just to show you the
        // loading of data in batches, it is not needed for the
        // solution
        if delay > 0 {
            presentLoader()
        }
        
        DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
            
            if delay > 0 {
                
                // dismiss the loader
                self.dismiss(animated: true, completion: nil)
            }
            
            // Calculate the page end based on the page size or on
            // the number of items remaining to load if the page size
            // is greater than the number of items remaining
            var pageEnd = self.pageStart + self.pageSize - 1
            
            if pageEnd > self.totalNumberOfItems.count {
                let remainingItems = self.totalNumberOfItems.count - self.pageStart - 1
                pageEnd = self.pageStart + remainingItems
            }
            
            let newItems = Array(self.totalNumberOfItems[self.pageStart ... pageEnd])
            self.itemsToLoad.append(contentsOf: newItems)
            self.pageStart = pageEnd + 1
            
            let indexPaths = newItems.map { IndexPath(row: $0,
                                                      section: 0) }
            
            // Update the table view
            self.tableView.beginUpdates()
            self.tableView.insertRows(at: indexPaths, with: .fade)
            self.tableView.endUpdates()
            
            // scroll to first newly inserted row
            if let firstNewRow = indexPaths.first {
                self.tableView.scrollToRow(at: firstNewRow,
                                           at: .top,
                                           animated: true)
            }
            
            
            // Unlock the loading process
            self.isLoadingItems = false
        }
    }
}

然后观察是否使用 scrollViewDidScroll 到达末尾并重新加载表格视图以显示插入的行

override func scrollViewDidScroll(_ scrollView: UIScrollView) {
    
    // Check that the current scroll offset is > 0 so you don't get
    // any false positives when the table view is set up
    // and check if the current offset has reached the end
    if scrollView.contentOffset.y >= 0 &&
        scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height) {
        
        print("reached end, load more")
        
        // Load more data
        loadItems(withDelay: 1)
    }
}

如下所示:

UITableView 分页重载 end of table view rollview swift iOS

如果您发现某些部分难以理解或添加到您自己的代码中,可以找到可以按原样运行的完整代码 此处

I believe you will have to do some pagination type of processing on your side with the help of scrollViewDidScroll to observe when you reach the end of a the tableview to load the next batch

Start by setting some initial variables to help you track the paging process.

var pageStart = 0
var pageSize = 15

// scrollViewDidScroll will be called several times
// so we need to be able to block the loading process
var isLoadingItems = false

// Array of 50 values which you get from the API
// For example your JSON data
var totalNumberOfItems = (0...49).reduce([Int]())
{ (result, number) in
    
    var array = result
    array.append(number)
    return array
}

// This will periodically be filled with items from totalNumberOfItems
var itemsToLoad: [Int] = []

I create this loading function which helps with adding the items in batches and reloading the tableview appropriately

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(true)
    loadItems()
}

private func loadItems(withDelay delay: Double = 0) {
    
    // Check that there are items to load
    if pageStart < totalNumberOfItems.count, !isLoadingItems {
        
        isLoadingItems = true
        
        // The delay and dispatch queue is just to show you the
        // loading of data in batches, it is not needed for the
        // solution
        if delay > 0 {
            presentLoader()
        }
        
        DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
            
            if delay > 0 {
                
                // dismiss the loader
                self.dismiss(animated: true, completion: nil)
            }
            
            // Calculate the page end based on the page size or on
            // the number of items remaining to load if the page size
            // is greater than the number of items remaining
            var pageEnd = self.pageStart + self.pageSize - 1
            
            if pageEnd > self.totalNumberOfItems.count {
                let remainingItems = self.totalNumberOfItems.count - self.pageStart - 1
                pageEnd = self.pageStart + remainingItems
            }
            
            let newItems = Array(self.totalNumberOfItems[self.pageStart ... pageEnd])
            self.itemsToLoad.append(contentsOf: newItems)
            self.pageStart = pageEnd + 1
            
            let indexPaths = newItems.map { IndexPath(row: $0,
                                                      section: 0) }
            
            // Update the table view
            self.tableView.beginUpdates()
            self.tableView.insertRows(at: indexPaths, with: .fade)
            self.tableView.endUpdates()
            
            // scroll to first newly inserted row
            if let firstNewRow = indexPaths.first {
                self.tableView.scrollToRow(at: firstNewRow,
                                           at: .top,
                                           animated: true)
            }
            
            
            // Unlock the loading process
            self.isLoadingItems = false
        }
    }
}

Then observe if you reached the end using scrollViewDidScroll and reload the tableview to show the inserted rows

override func scrollViewDidScroll(_ scrollView: UIScrollView) {
    
    // Check that the current scroll offset is > 0 so you don't get
    // any false positives when the table view is set up
    // and check if the current offset has reached the end
    if scrollView.contentOffset.y >= 0 &&
        scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height) {
        
        print("reached end, load more")
        
        // Load more data
        loadItems(withDelay: 1)
    }
}

Here is how that will look:

UITableView paging reload end of table view scrollview swift iOS

If you found some part difficult to follow or add into your own code, the complete code which can run as is can be found here:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文