What does contentOffset do in a UIScrollView?

Viewed 47143

What is the use of the contentOffset property in UIScrollView?

3 Answers

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.

Related