SwiftUI List Infinite Scrolling within 80 lines of code!

KD Knowledge Diet
2 min readMay 31, 2022

Infinite scrolling is one of the essential techniques for almost any production level app. If you develop with SwiftUI, you can see the magic of reducing the amount of code from 200 lines to 300 lines to 60 lines. So don’t be afraid, it’s pretty easy.

API

If you increment a number in your query like page=2 , this api will send you another twenty data.

Integrate API in your ViewModel

ViewModel

I won’t explain URLSession in this tutorial. But take a look at shouldLoadData(id: Int) -> Bool. You can customize this function by subtracting more numbers. What this means is a flag that determines when data is loaded when scrolling. So when the scroll position arrives at numbers.count — 2, URLSession will call https://island-bramble.glitch.me/data?page=n.

Creating View

View Code

As soon as InfiniteScrolling View appears, it fetches API with the page number 1. And then when scrollview arrives at the numbers-count — 2, it will increment currentPage and load more data.

Conclusion

  1. Create a flag to determine when to fetch data
  2. Increment Page when scroll positions arrived at your defined position
  3. Fetch data

Please, if you don’t understand it, run the real project.

--

--

KD Knowledge Diet

Software Engineer, Mobile Developer living in Seoul. I hate people using difficult words. Why not using simple words? Keep It Simple Stupid!