Looking for good programming challenges?

Use the search below to find our solutions for selected questions!

Understanding the contentOffset and contentInset properties of the UIScrollView class

Sharing is caring!

In order to better understand the purpose of these two properties, it is important that we understand the contentSize property. The scroll view must know the size of the content view. This is important because the size of the content view can be larger than the visible area (example: screen) and the scroll view needs to know when to stop scrolling.

Take a look at the image bellow. The content view is marked using ‘#’ where as the scrollable area (example: screen) is marked using ‘-‘:

As you can clearly see, the content that we want to display in the scroll view doesn’t entirely fit in the scrollable area so we need to scroll in order for us to view the content.

The Apple documentation describes contentOffset as follows:
var contentOffset: CGPoint
“The point at which the origin of the content view is offset from the origin of the scroll view.”

In other words it defines the point in the content view that is visible at the top left of the scroll view bounds. We can use this property to scroll programmatically .

So for example:

The Apple documentation describes contentInset as follows:
var contentInset: UIEdgeInsets
“The distance that the content view is inset from the enclosing scroll view.”

In other words it is the distance that the content view is inset from the enclosing scroll view (padding). So, if you want to add more scrollable space at the bottom or at the top, you can use the property contentInset.top and contentInset.bottom, so you can add some extra space without changing the content size. It is important to note that through the contentInset we add more scrollable space. So an contentInset.top = 10 will add an extra space of 10 at the top. One way to think of it is “how much to shift the content down the scroll view when we’re scrolled all the way to the top”. When we scroll down this padding also scrolls along with the rest of the content.

Creating and Configuring Scroll Views

UIScrollView Class Reference