Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift ios add infinite scroll pagination to uitableview

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

like image 627
user2636197 Avatar asked Aug 29 '16 20:08

user2636197


People also ask

How can I add pagination in iOS?

Setting up for pagination in swift Let's create an Xcode project, add a table view in the Main storyboard. Create TableViewCell and Xib. After that, register TableViewCell and assign delegate and dataSource. Your TableViewCell.

What is UITableView in Swift?

A view that presents data using rows in a single column. iOS 2.0+ iPadOS 2.0+ Mac Catalyst 13.1+ tvOS 9.0+


1 Answers

Looks like amar’s answer might be a better solution now, but here’s my answer from 2017 anyway:

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...

like image 200
lukkea Avatar answered Oct 14 '22 21:10

lukkea