滚动以加载数据。迅速。 UITableView的

时间:2016-04-24 03:12:50

标签: swift uitableview tableview reloaddata

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

基本上,我希望表格在滚动到总元素时加载下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()
    }
}

1 个答案:

答案 0 :(得分:0)

Personally I'd change this if statement slightly.. What you're looking to do is load 10 cells when you're 5 away from the bottom only.. but it's slightly dangerous as it could easily load multiple times.

You need an external var to show the highest successful load you've done so far and check

if indexPath.row == currentResultsTitleArray.count - 6 && indexPath.row > self.highestIndexFetchedOn should be the trigger, then on a successful fetch, just before reload data, set self.highestIndexFetchedOn to the new indexPath.row

It's not clear what rowPerPage does but I'm guessing it's 10 and also the minCount logic looks right, but I'd print that out to make sure you're getting what you expect.

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()
}

I'm not sure about the data structure here with all these arrays housing the different data either... I think one array of dictionaries that have all the values in would be better and simplify what we're looking at.. but I can't say 100% without seeing the rest of the class..