Chapter 4
Infinite Scrollview

Estimated Time


Sometimes you want a regular scrollview, other times you want one that just keeps going and going and going. An infinite scrollview is one where its content loops back to the beginning after it passes the end of its list of items (and vice versa).

In this chapter you will learn how to override the layoutSubviews() method of UIScrollView and update the scrollview’s position if needed.

The content size includes all 12 “screens”

Beyond Bounds

The point of an infinite scrollview is to have the screen not bounce in either direction, but rather loop to its beginning or end depending on the scroll direction.

To do this you need to know:

  1. How much content is there (i.e. your view’s contentSize)
  2. How many “screens” worth of content there is, which you’ll calculate.
  3. Where, at any given point, the user has currently scrolled to (you measure this via the view’s currentOffset)

In this example, the content size includes all 12 frames.

The Rules

There are 2 rules you need to follow:

  1. What to do when a user scrolls past the end of the content
  2. What to do when a users scrolls past the beginning of the content

Behaviour of a ScrollView

The behaviour of a UIScrollView is quite simple: whenever a user is scrolling, the view is updating a variable called contentOffset and figuring out whether or not it needs to render new content.

Less Than The Beginning

You’re going to constantly check if the content offset is less than the origin point of the view:

1
2
3
if contentOffset.x < 0 {
	//move content to the end 
}

In this example, contentOffset.x is less than 0 (the origin of the content view).

Greater Than The End

You are also going to check if the content offset is greater than the end of the entire content:

1
2
3
if contentOffset.x > totalWidth - view.width {
	//move content to the beginning
}

This step is a bit different than the previous because contentOffset refers to the origin point of the view. It is officially described as:

The point at which the origin of the content view is offset from the origin of the scroll view.

So, the point at which the origin of the content view is “past” the end point is when the origin + the content view’s width is past the end.

In this example, the contentOffset + width of the app's screen is past the end point.

Build it.

You’re ready to build the infinite scrollview. As you’ll see, there isn’t much to it – just a few short lines of code. The magic happens elsewhere.