Chapter 3
Plan It!
Get your goggles on as we start diving into the code with C4.
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”
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:
contentSize
)currentOffset
)There are 2 rules you need to follow:
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.
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
}
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.
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.