What does contentOffset do in a UIScrollView?

It could be considered as the coordinate of the origin of scrollView's frame relative to the origin of its contentView's frame. See the picture below:

enter image description here


According to the documentation, the contentOffset property represents:

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

In plain speak, it's how far the view has moved in each direction (vertical and horizontal). You can unpack vertical and horizontal distance by accessing the x and y properties of the CGPoint:

CGFloat xOffset = _myScrollView.contentOffset.x;
CGFloat yOffset = _myScrollView.contentOffset.y;

enter image description here

Here you see two rectangles:

  • the visible area
  • the total area

Scrolling is changing the origin of the visible area within the total area.

In iOS all views have a visible area represented by the view.bounds rectangle. The class UIScrollView is a view with an unique property: it has a second rectangle called “content view” with a size bigger than its bounds. Thus, in a scroll view:

  • the visible area is scrollView.bounds
  • the total area is called content view, whose size is scrollView.contentSize

contentOffset is another name for scrollView.bounds.origin, implemented as follows:

var contentOffset: CGPoint { 
    get { return bounds.origin }
    set {
        var bounds = self.bounds
        bounds.origin = newValue
        self.bounds = bounds
    }   
}

When we change the contentOffset programmatically, we are also changing the bounds.origin, which causes a different area of the content view to be rendered. If we animate this change with setContentOffset(pt, animated: true), the scrollView appears to scroll as dragged by the user’s finger.

The official documentation defines contentOffset like this (italics are mine):

contentOffset: The point at which the origin of the content view (the total area) is offset from the origin of the scroll view (the visible area).

I’d like to highlight the comment of @westsider on the accepted answer:

For instance, if you want to present n pages that can be scrolled through, you create a UIScrollView with contentSize (n*pageWidth, pageHeight) and with bounds size (pageWidth, pageHeight). You then set contentOffset.x = (n-1) * pageWidth with n = 1 to display the first page.