Parallax ScrollView In Swift

This week I got a chance to work on a personal project that involved UICollectionView. In particular, I implemented a simple parallax effect inside of a an UICollectionViewCell. For the curious ones, Parallax effect became popular thanks to Web Designers who started the trend in 2011 using HTML 5 and CSS3.

I should mention that parallax effect is not for everyone and should be used sparingly (remember when it was introduced on an iPhone and how it made some people “dizzy”?). It is quite a nice feature though.

For those of you who would like to just skip to the actual code sample, here is the link to my project on GitHub. Here is a brief tutorial and important pieces that make parallax work.

Before tackling any project, I find it helpful to brake a project into smaller tasks. There are two important steps to this tutorial:

  1. Setup the initial collection view with data source.
  2. Implement the parallax effect.

Start by creating a new project called ParallaxScrollView using Single View Application template. After Xcode creates the project, you will have AppDelegate, ViewController, Main storyboard and a whole bunch of other files.

Go to your Main.storyboard and replace the ViewController created by Xcode with CollectionViewController. Set the size of the table view to compact:


Resize the cell to take up the width of the CollectionView and height of 160 points:


Make sure the cell is still selected, set the identifier to:

Add UIImageView to the cell and resize it to 320 by 200 points (yep, we are making UIImageView taller then the actual cell).


Next, set the content view mode to Aspect Fill. This is very important.


We are going to create a custom cell now. Got to File > New > File and select Cocoa Touch Class template. Give it a name ParallaxCollectionViewCell and make sure it inherits from UICollectionViewCell.

Select ParallaxCollectionViewCell class and add global constants just below the import UIKit line:

Declare an outlet for your UIImageView instance:

Image variable that will hold your image (we are taking advantage of didSet to set the imageView’s image as soon as the actual image is set via view controller):

Implement the offset function that will offset the image view:

Select the ViewController and change it to inherit from the UICollectionViewController. Declare a constant right below the import UIKit line:

Declare an array that will hold paths to your sample images (we will add images later).

Next, download sample images and add them to your project. In you ViewController, add the following to your viewDidLoad: function:

Implement required Data Source functions:

Next, implement UIScrollView Delegate method:

Run your project. Try scrolling. Pretty awesome, huh?

Parallax ScrollView In Swift