How to add Load More / Infinite Scrolling in iOS using Swift
- October 14, 2019
- John Codeos
In this tutorial, I’ll show you how to add the Load More/Infinite Scrolling feature into your TableView/CollectionView very easy by using the scrollViewDidScroll, in TableView, and the willDisplay in CollectionView.
We already have an UITableview filled with data, and we want to add the Load More/Infinite Scrolling feature.
First, we create an UITableViewCell with a Xib file and add an UIActivityIndicatorView on the center of the cell.
Control+left click and drag the UIActivityIndicatorView into your .swift file and give the name activityIndicator…
…and add ‘loadingcellid‘ as Identifier.
Now, let’s go into our TableViewController where we have the UITableView, and register the Loading Cell in the viewDidLoad().
In the UITableView’s delegate and datasource we add in the method numberOfRowsInSection the following code.
..and we return 2 sections(one for the items, and one for the Loading Cell).
In the cellForRowAt method we returning the cell for each section:
…and also we set the row height.
Next, we use the method scrollViewDidScroll, from the embedded UIScrollView in the UITableView, to detect when the user is close to the end of the list to call the method…
… loadMoreData() to download more data.
In this example we use the footer as Loading View using a ReusableView.
We already have a CollectionView filled with data.
First, we create an UICollectionReusableView and add an UIActivityIndicatorView on the center of that view.
Control + left click and drag the UIActivityIndicatorView into your .swift file and give the name activityIndicator.
and add ‘loadingresuableviewid‘ as Identifier.
Now, let’s go into our CollectionViewController where we have the UICollectionView, and register the Loading ReusableView in the viewDidLoad().
In the UICollectionView‘s delegate and datasource, add the following method to return the size for the Loading View when it’s time to show it.
Set the reusable view in the CollectionView footer…
..and we start and stop the activityIndicator‘s animation when the footer appears and disappears, respectively.
Finally, we set the time we want more data to load while we scroll. In this example, it’ll load more data when the user sees the 10th cell from the bottom.
You can find the final project here
If you have any questions feel free to DM me on Twitter @johncodeos or leave a comment below!