Scroll View with Paging Tutorial in iOS8 with Swift

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 built for iOS8.1 with Xcode 6.1

Open Xcode and create a new Single View Application. For product name, use IOS8ScrollViewPagingTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Select Swift as Language and make sure iPhone is selected in Devices.

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

var colors:[UIColor] = [UIColor.redColor(), UIColor.blueColor(), UIColor.greenColor(), UIColor.yellowColor()]
var frame: CGRect = CGRectMake(0, 0, 0, 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 = self.scrollView.frame.size.width * CGFloat(index)
      frame.size = self.scrollView.frame.size
      self.scrollView.pagingEnabled = true
      var subView = UIView(frame: frame)
      subView.backgroundColor = colors[index]
      self.scrollView .addSubview(subView)
    self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * CGFloat(colors.count), self.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 ScrollViewWithPaging at the ioscreator repository on github.