Pagination in SwiftUI
Pagination is the technique to divide large response into discrete pages with limited data on each page.
For example: Suppose there is an API that returns 1000 records in response. Instead of returning all 1000 records in one go, can divide records into multiple pages say 20 pages in total where each page has 50 records.
In this way, the app is making a request which returns 50 records at a time.
In this article, we are going to consume the “LIST USERS” API available at https://reqres.in
The response has the following information: “total_pages”, “per_page”, “page” etc along with the list of users.
In this article, we will follow MVVM with SwiftUI to implement Pagination.
We are going to create and display a list of users returned by the API. Since API is returning 6 users per page, hence, initially we will have 6 users on the list. On scroll will fetch another set of users for the subsequent page and continues till we reach the last page.
Create Users Model
This is the response model and is the single source of truth for the view.
Create User View
This is the user cell in the Users list.
Create User List
As we have created our User cell, now we are going to create a list of users using ScrollView and LazyVStack.
Before proceeding further let's understand few important points in the above code.
Line 6: Creating an instance of
UsersViewModel. Here UsersViewModel is the Observable Object which you will get to know in the next piece of code. Now, whenever published properties of the observable object change, SwiftUI updates the part of the view that depends on those properties.
Line 13: View redraws itself whenever there is a change in the
Line 16: Calls a function
loadMoreContent whenever a row is visible on the screen.
Users View Model
In the ViewModel, we are going to handle the logic of Pagination.
The main logic for the pagination lies in the lines 13–20, where thresholdIndex is the key parameter for calling an API again.
NOTE : Here
usersis the published property which we discussed earlier, whenever it changes SwiftUI updates
The rest of the code is self-explanatory.
This is how it looks finally 👇
You can find the complete source code of the project at
This repository contains SwiftUI examples. Contribute to apoorv487/SwiftUI development by creating an account on…
Make sure you give this post 50 claps 👏 and follow if you enjoyed reading and want to read and learn more.
Thank you for reading. ❤️
Connect with me: LinkedIn