Scroll View iOS Tutorial

A Scroll View provides support for displaying content that is larger than the size of the application’s window. In this tutorial a large image is added inside a Scroll View. This image can be panned around. This tutorial is made with Xcode 10 and built for iOS 12.

Open Xcode and create a new Single View App.

For product name, use IOS12ScrollViewTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

Download the image and drag it from the Finder to the Assets Library. Go to the ViewController.swift file and add the follwing properties

var imageView: UIImageView!
var scrollView: UIScrollView!

Change the viewDidLoad method to

override func viewDidLoad() {     
  super.viewDidLoad()
  // 1   
  imageView = UIImageView(image: UIImage(named: "strandvagen.jpg"))    
  // 2
  scrollView = UIScrollView(frame: view.bounds)
  scrollView.backgroundColor = UIColor.black
  // 3
  scrollView.contentSize = imageView.bounds.size
  // 4      
  scrollView.addSubview(imageView)
  view.addSubview(scrollView)
}
  1. The large image is added to the Image View

  2. A Scroll View is initialized with the size of the whole screen and a black background color

  3. The contentSize property is the size of the content that you need to display in the scroll view.

  4. The Image View is added as a subview of the Scroll View which is added as a subview of the main View.

Build and Run the project and pan around to view different portions of the image.

You can download the source code of the IOS12ScrollViewTutorial at the ioscreator repository on Github.