Creating a Scroll View

The scroll view’s subviews are positioned with respect to its bounds origin. The scroll view knows how far it should be allowed to slide its subviews downward and rightward — the limit is reached when the scroll view’s bounds origin is {0,0}. What the scroll view doesn’t know is how far it should be allowed to slide its subviews upward and leftward. To tell it, you set the scroll view’s contentSize. The scroll view uses its contentSize, in combination with its own bounds size, to set the limits on how large its bounds origin can become. In effect, the contentSize is how large the scrollable content is. If a dimension of the contentSize isn’t larger than the same dimension of the scroll view’s own bounds, the content won’t be scrollable in that dimension: there is nothing to scroll, as the entire scrollable content is already showing. A remarkable feature of autolayout (Chapter 14) is that it can calculate the contentSize for you based on the constraints of the scroll view’s subviews.

To illustrate, I’ll start by creating a scroll view and providing it with subviews entirely in code. In the first instance, let’s not use autolayout. Our project is based on the Empty Application template. Add a UIViewController subclass, ViewController, with no nib. In the app delegate’s application:didFinishLaunchingWithOptions:, we do the usual dance to get ourselves a root view controller:

self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]]; // Override ...

Get Programming iOS 6, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.