Scroll View with Paging iOS Tutorial

Scroll Views in combination with paging enabled allows the user to scroll page by page. In this tutorial we will create some views, which can be scrolled using paging.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 IOSScrollViewPagingTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

Go to the Storyboard, drag a Scroll View from the Object Library to the View Controller inside the Storyboard. 

Open the Assistant Editor and make sure the ViewController.swift file is visible. Ctrl + drag from the Scroll View to the ViewController class and create the following Outlet

In The ViewController class add the following properties

let colors = [,,, UIColor.yellow]
var frame = CGRect(x: 0, y: 0, width: 0, height: 0)

An Array containing colors and an empty CGrect are created. Next, change the viewDidLoad method to.

override func viewDidLoad() {

    for index in 0..<colors.count {
        frame.origin.x = scrollView.frame.size.width * CGFloat(index)
        frame.size = scrollView.frame.size

        let subView = UIView(frame: frame)
        subView.backgroundColor = colors[index]

    scrollView.contentSize = CGSize(width: scrollView.frame.size.width * CGFloat(colors.count), height: scrollView.frame.size.height)

The for loops iterates through the color array, where each color is used as the background of an UIView. These views are then added as a subview of the Scroll View. The paging is enabled with the pagingEnabled property. Build and Run the project. Swipe right to scroll through the colored views, page by page.


You can download the source code of the IOSScrollViewPagingTutorial at the ioscreator repository on github.