Infinite UIScrollView

aybek can kaya
3 min readMay 20, 2019

--

In lots of apps, you may faced with a scrollview that never ports itself to the opposite direction at the end of the content size. This technique is very usual for many years, on many platforms. On the other hand, there are lots of third-party libraries to get this effect. You do not really need any third party library. This technique has very simple logic. Trust me :)

Paging enabled UIScrollView enables the user to view its content page by page. UIScrollView enables this effect by adjusting the scrollView’s offset when the user ends dragging. As user scroll to the end of pages (to the right side), scrollview limits to exceed its content by moving its offset to opposite direction with such beautiful animation.

We want scrollview to not limit its content offset when user wants to exceed its content size. So we need to add two more pages to UIScrollView. The last page will be added to index zero, and the first page will be added to the index (numberOfItems + 1). Then, if the user views the page “numberOfItems” scrollview content offset x is set to 0. If the user views the index of 0, then scrollView content offset x will be set to “pageSize * numberOfItems”.

Let’s coding :)

The first thing we will be doing is to create a new class that is inherited from UIView.

BannerView should be like below:

There is nothing unusual here. Now, we should add the scrollView and setUp code for BannerView:

I have used frames instead of auto layout for simplicity. Also, I have used closures instead of delegates. This helps to avoid dirt from the code at ViewController. With closures, you may simply use bannerView like this:

For UIScrollView delegation I will use scrollViewDidEndDecelerating(_ scrollView: UIScrollView) instead of scrollViewDidScroll(_ scrollView: UIScrollView). Because we do not need to calculate the paging position at each scrollView movement.

And finally, our code will be like this for BannerView.swift:

Summary

As a summary, we have made a reusable scrollview component with a little logic. By the way, with huge amounts of data, it should be better to use UICollectionView. Because UICollectionView has better performance and better memory management than UIScrollView. Also, you can expand InfiniteScrollView with timing or bidirectional scrolling options. With a little improvement, it would be a really reusable tool for your applications.

Full Source Code can be found at

Happy Coding :))))

--

--