Scroll Views

Scroll views are used when content that needs to be displayed won’t fit in its entirety on the screen. The UIScrollView class provides functionality to:

  • Scroll through content that is bigger than the size of the view, using pan gestures.
  • Zoom in and out of content, using pinch gestures.

Scrolling

Scrolling is fairly straightforward, no special delegation or gesture recognizers are required. The UIScrollView simply scrolls its subviews.

  1. Add a UIScrollView to the display.
  2. Build some subviews, setting their frame property to position them in the scroll view.
  3. Set the scroll view’s contentSize property to a value great enough to cover all the subviews. contentSize does not get set automatically and defaults to CGSizeZero, so don’t forget this step!
Header Source

Steps 1 and 2 can be performed in the Interface Builder as well, but step 3 must be done in code.

We can retrieve the content offset using the bounds or contentOffset properties.

We can update our ViewController to conform to the UIScrollViewDelegate protocol, and read out the content offset whenever it changes by implementing - (void)scrollViewDidScroll:(UIScrollView *)scrollView.

Header Source

Zooming

Zooming requires a couple of extra steps.

  1. Set the scroll view’s minimumZoomScale and maximumZoomScale properties.
  2. Register a delegate on the UIScrollView which implements - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView.

That’s all it takes to zoom using the pinch gesture. If you need to support additional gestures (for example, double-tap to zoom all the way out), you will need to add the corresponding UIGestureRecognizer on the scroll view.

Manually Scrolling and Zooming

As a final exercise, let’s programmatically add a couple of UIButtons to the view for saving and restoring the current scroll offset and zoom scale.

Comments are closed.