SwiftUI Pagination
Pagination in SwiftUI
Pagination in SwiftUI using ScrollView and LazyVStack with MVVM
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.
Let’s begin:
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.
SwiftUI Implementation
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 users
property.
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
users
is the published property which we discussed earlier, whenever it changes SwiftUI updatesUsersView
.
The rest of the code is self-explanatory.
This is how it looks finally 👇
Source Code:
You can find the complete source code of the project at
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