ScrollView With Paging

In this tutorial, we're going to create a bunch of views, each with a different color. You can scroll through the views horizontally. The views layed out next to each other will look like this.

Update: Oct 24, 2014. The rewritten version in Swift for iOS 8 and Xcode 6 is available here.

Create a new Project, select Single View Application, choose Next.

Enter the following

Open XIB. Drag a ScrollView from the Object Library to the UIView.

Ctrl-drag from the ScrollView to ViewController.m between the @interface and @end sections and make the following connection.

Enter the viewDidLoad method

- (void)viewDidLoad 
[super viewDidLoad];
NSArray *colors = [NSArray arrayWithObjects:[UIColor redColor], [UIColor blueColor], [UIColor greenColor],[UIColor yellowColor] , nil];

for (int i = 0; i < colors.count; i++)
CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * i;
frame.size = self.scrollView.frame.size;
self.scrollView.pagingEnabled = YES;

UIView *subview = [[UIView alloc] initWithFrame:frame];
subview.backgroundColor = [colors objectAtIndex:i];
[self.scrollView addSubview:subview];

self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * colors.count, self.scrollView.frame.size.height);

First we create an array of colors. We loop to each color where we create a subview which we'll we add to the scrollview. The UIScrollView class supports a paging mode, which restricts a user initiated scroll action to scrolling a single screens worth of content at a time. With the pagingEnabled property we'll enablepaging.

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