DEV Community

Gus Eulalio
Gus Eulalio

Posted on

Building a pseudo-infinite scroller

So you were given the task of building an infinite table view or carousel, and they want it for yesterday. Now you're scratching your head wondering about the inner workings of a table view.

Fret not. There's a quick solution for this, or a temporary workaround while you don't build the real thing.

What we'll do

We'll make a table view 10,000 cells long, point the viewing window to the middle of the collection, and cycle through the data source.

Before we start

I won't build anything from scratch here. I'll consider you have a working table view (or collection view) that you want to convert into an infinite scroller.

I'll do this based on a table view, all changes are made on the table view controller / data source. It isn't much different for using a collection view.

How to

First up, go to your tableView(tableView:, cellForRowAt:) method, and replace the instances of indexPath.row, with indexPath.row % datasource.count.

This will make sure you keep getting data when the table view asks for an element outside the datasource range.

Next, create the constant below:

let numberOfCells = 10_000
Enter fullscreen mode Exit fullscreen mode

This will be the size of your table view. The user can obviously reach the end of the table view, but it will take them scrolling for a long time in one direction, which is an unlikely behaviour.

Then replace tableView(tableView: numberOfRowsInSection:) with:

override
func tableView(_ tableView: UITableView,
               numberOfRowsInSection section: Int)
-> Int
{
    return numberOfCells
}
Enter fullscreen mode Exit fullscreen mode

Next, add the following line to viewDidLoad() to avoid revealing our secret:

tableView.showsVerticalScrollIndicator = false
Enter fullscreen mode Exit fullscreen mode

This will hide the scroll indicator, which would indicate to the user that they're not really seeing an infinite table view.

And to finish up, add the below to viewDidAppear(:):

let indexPath = IndexPath(row: numberOfCells / 2, section: 0)
tableView.scrollToRow(at: indexPath, 
                      at: .top, animated: false)
Enter fullscreen mode Exit fullscreen mode

This last part will point the scroll view to the middle of the table.

There you go, now you can run it and see it working yourself.

Limitations

Again, this isn't a truly infinite table view. Even though it's hard to reach the ends of the table in any real-life scenario, this is still a possible scenario, especially if you need to programmatically manipulate the scroll position for some reason.

Also, you may think 10,000 is a small number and want some extra leeway. That's fine, but don't go too crazy, there is an increase in the memory footprint, and it may get slow quickly especially in old hardware.

Hope you find this useful.

Top comments (0)