【问题标题】:Scroll to load data. Swift. UITableView滚动以加载数据。迅速。 UITableView
【发布时间】:2016-04-24 03:12:50
【问题描述】:

我的代码在通过滚动表加载数据到某一行时出现了一些问题,但我找不到原因。

基本上,我希望表格在滚动到总元素 - 5 时加载接下来的 10 个元素。例如,我希望表格最初加载 10 个元素。然后,当它碰到第五个元素时,它会加载 11-20 个元素。

我的问题是当我最初加载表格时,它只加载前 5 个元素,但我可以看到 6-10 之间有一些空格,然后我将表格滚动到第五个元素,它加载接下来的 10 个元素( 6 - 15)。

let rowPerPage = 10

func refreshResults(){
    // append data from server //
    self.resultsTitleArray.append(...)

    if self.resultsTitleArray.count != 0 {
        let minCount = min(rowPerPage, self.productImageArray.count) - 1
        self.currentResultsTitleArray += self.resultsTitleArray[0...minCount]
    }

    self.resultsTable.reloadData()
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
    return currentResultsTitleArray.count
}

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    let diff = rowPerPage - 5
    let currentDiff = currentResultsTitleArray.count - 1 - indexPath.row
    if currentResultsTitleArray.count != resultsTitleArray.count && diff == currentDiff {
        let minCount = min(resultsTitleArray.count, currentResultsTitleArray.count + rowPerPage as Int) - 1
        let next = self.currentResultsTitleArray.count
        self.currentResultsTitleArray += self.resultsTitleArray[next...minCount]
        resultsTable.reloadData()
    }
}

【问题讨论】:

    标签: swift uitableview tableview reloaddata


    【解决方案1】:

    就我个人而言,我会稍微更改此if 声明。您要做的是仅在距离底部 5 处时加载 10 个单元格。但这有点危险,因为它可以轻松加载多次.

    你需要一个外部的var 来显示你迄今为止完成的最高成功负载并检查

    if indexPath.row == currentResultsTitleArray.count - 6 && indexPath.row > self.highestIndexFetchedOn 应该是触发器,然后在成功获取时,在重新加载数据之前,将 self.highestIndexFetchedOn 设置为新的 indexPath.row

    不清楚rowPerPage 做了什么,但我猜它是10minCount 逻辑看起来是正确的,但我会打印出来以确保你得到你所期望的。

    if indexPath.row == currentResultsTitleArray.count - 4 && indexPath.row > self.highestIndexFetchedOn {
    
        let minCount = min(resultsTitleArray.count, currentResultsTitleArray.count + rowPerPage as Int) - 1
        let next = self.currentResultsTitleArray.count
    
        print("Count:",minCount)
    
        self.currentResultsTitleArray += self.resultsTitleArray[next...minCount]
    
        // etc...
    
        self.highestIndexFetchedOn = indexPath.row
        tableView.reloadData()
    }
    

    我不确定这里的数据结构,所有这些数组都包含不同的数据......我认为一个包含所有值的字典数组会更好,并简化我们正在查看的内容......但我不能说 100% 没有看到班上的其他人..

    【讨论】:

      猜你喜欢
      • 2020-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多