Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView Pagination - Bottom Refresh to Load New Data in Swift

I am trying to implement loading data from my backend with pagination. I have seen this, but it loads all the data, all then time. Is this the right way or am I doing something wrong?

Thanks in advance.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell

    print(indexPath.row)

    if (indexPath.row + 1 < self.TotalRowsWithPages) {
        cell.textLabel?.text = "\(self.myarray!.[indexPath.row].body)"
    } else {

        cell.textLabel?.text = "Loading more data...";

        // User has scrolled to the bottom of the list of available data so simulate loading some more if we aren't already
        if (!self.isLoading) {
            self.isLoading = true;
            self.TotalRowsWithPages = self.TotalRowsWithPages + self.PageSize
            self.getmoredata()
        }
    }

    return cell
}
like image 682
Chris G. Avatar asked Feb 19 '16 01:02

Chris G.


2 Answers

Nope, you can't go with that approach because cellForRowAtIndexPath is called many times and also it will take much time to check your conditions!

Here, I have found a better option for UITableView pagination.

func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {

    //Bottom Refresh

    if scrollView == tableView{

        if ((scrollView.contentOffset.y + scrollView.frame.size.height) >= scrollView.contentSize.height)
        {
            if !isNewDataLoading{

                if helperInstance.isConnectedToNetwork(){

                    isNewDataLoading = true
                    getNewData()
                }
            }
        }
    }
}

isNewDataLoading is Bool to check that UITableView is loading new data or not!

Hope this helps!

like image 101
Sohil R. Memon Avatar answered Sep 21 '22 04:09

Sohil R. Memon


You should implement load more in tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath). When last cell loading is display it mean user scroll to bottom so this is time you need load more data.

Maybe it looks like this:

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {

    if !(indexPath.row + 1 < self.TotalRowsWithPages) {
        self.isLoading = true;
        self.getmoredata()

    }
}
like image 21
vien vu Avatar answered Sep 20 '22 04:09

vien vu