【问题标题】:Swift create pagination in UITableViewSwift 在 UITableView 中创建分页
【发布时间】:2018-11-29 12:19:00
【问题描述】:

我有 UITableView 显示来自数组的缓存数据

我想像这样的结构在UITableView 上进行分页:

1)当我使用 UITableView 查看时 - 它会显示所有缓存数据(我这样做了,并且有效)

2) 当用户向下滚动并 if caching data left 5 调用函数时,将新的 10 个数据加载到数组并显示在 UITableView 的底部并添加重新检查(当表行显示 20 行中的 15 行时调用函数以加载更多数据并添加)

例如:在缓存数组中我有 10 个数据,函数加载新和 表格显示了 20 行数据

我尝试这样做:

public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        print(indexPath.row)

        let lastItem = array.count - 1
        if indexPath.row == lastItem {
            loadMoreData()
        }
    }

 func loadMoreData {
        for _ in 0...9 {
            //load data from server
        }
       tableView.reloadData()
    }

【问题讨论】:

  • 你有什么问题?
  • @SPatel 如何在最后创建左到 5 行的检查并需要添加更多数据?
  • @SahilManchanda 我不需要将页码发送到服务器,我需要加载更多
  • 分页应该从后端完成。您只需将参数与pageNo 一起传递,以指定您想要哪个页面的数据。因此,在调用 api 后,您需要在当前数据源中追加数据并增加页码。数一数。页码计数可以由您自己的逻辑管理。

标签: ios swift uitableview pagination


【解决方案1】:

使用一个布尔变量来检查数据是否从 api 加载。

var isLoading = false

添加以下代码:

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    if !isLoading && indexPath.row == array.count - 5 {
        isLoading = true
        loadMoreData()
    }
}

从 api 获取数据后设置isLoading = false

希望对你有帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-10
    • 1970-01-01
    • 2017-03-06
    • 1970-01-01
    • 2020-01-04
    • 2016-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多