swift ios add infinite scroll pagination to uitableview

user2636197 picture user2636197 · Aug 29, 2016 · Viewed 28.1k times · Source

I wonder if tableview has any built-in function to add infinite scroll/pagination.

Right now my VC looks like this:

var data: JSON! = []

override func viewDidLoad() {
    super.viewDidLoad()

    //Init start height of cell
    self.tableView.estimatedRowHeight = 122
    self.tableView.rowHeight = UITableViewAutomaticDimension

    self.tableView.delegate = self
    self.tableView.dataSource = self

    savedLoader.startAnimation()
    //Load first page
    loadSaved(1)

}

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

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("aCell") as! SavedTableViewCell

    let info = data[indexPath.row]
    cell.configureWithData(info)

    return cell
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    performSegueWithIdentifier("WebSegue", sender: indexPath)

    tableView.deselectRowAtIndexPath(indexPath, animated: false)
}

I fetch my data using loadSaved(1) by giving the function the current page I want to load. The function makes a API request using alomofire then populate the var data: JSON! = [] with the data that should be displayed

So what I want to do is when I scroll to the bottom of the tableview loadSaved(2) should be called loading more data into the tableview

Answer

lukkea picture lukkea · Mar 20, 2017

The UITableViewDelegate has a table​View(_:​will​Display:​for​Row​At:​) instance method which "tells the delegate the table view is about to draw a cell for a particular row."

In your case I would use it something like this:

override open func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if indexPath.row == data.count-1 { //you might decide to load sooner than -1 I guess...
      //load more into data here
    }
}

Depending on your code, you may need some checks around this to ensure you don't end up in an infinite loop if you've loaded all your data...