Mobile Development

UIScrollView

The UIScrollView can be used explicitly with the control from the Object Library and manual creation through code. UIScrollView is also included within UITableView, UIWebView and UICollectionView.

So why use a scroll view, why are scroll views included in UITableView?

UIScrollView provides a mechanism to display content that is larger than the size of the application’s window and enables users to scroll within that content by making swiping gestures. [1]

UIScrollView has two sizes

  1. Frame size which is the size of its presentation
  2. Content size which is the size of the content within the scroll view.

As long as the content size is larger than the frame size, UIScrollView allows the user to pan around the images or other content within the control.

[Video] - Zoom and pan large images - UIScrollView

Let's dive in and watch a developer go through the process of creating a UIScrollView and watch the developer add a large image to pan and zoom. ITC 2 of 2

Here is another example of a very similar use case, but with a different implementation style.

Code

Below is an example of configuring a UIScrollView with a large UIImage loaded from Wikicommons.

import UIKit

let imageURL = NSURL(string: "http://upload.wikimedia.org/wikipedia/commons/5/5c/Double-alaskan-rainbow.jpg")
let imageData = NSData(contentsOfURL: imageURL!)
let largeImage = UIImage(data: imageData!)
let imageView = UIImageView(image: largeImage)
print("imageView size is \(imageView.bounds)")

let scrollView = UIScrollView(frame: CGRectMake(0, 0, 300.0, 300.0))
scrollView.addSubview(imageView)
scrollView.contentSize = imageView.bounds.size
print("scrollView frame is \(scrollView.frame)")
print("scrollView scrollable content size is \(scrollView.contentSize)")

The last two lines demonstrate that even though the view frame of the UIScrollView is 300x300, the content will scroll to the UIImageview size of 1919x1008

The UIScrollView functionality is more than just images, of course. You can create more powerful examples such as paging views and utilize delegate callbacks to observe notifications on scrolling behavior.

References

[1] UIScrollView Class https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIScrollView_Class/index.html

[2] Scroll View Programming Guide for iOS https://developer.apple.com/library/ios/documentation/WindowsViews/Conceptual/UIScrollView_pg/Introduction/Introduction.html