Setting up UIScrollView to swipe between 3 view controllers

UPD: June, 2015
Swift

The concept remains the same, which is described below in Objective-C section. There is a little change in syntax. To add childviewcontroller use following snippet:

let aViewController = storyboard.instantiateViewControllerWithIdentifier("A") as! AViewController;

addChildViewController(aViewController);
scrollView!.addSubview(aViewController.view)
aViewController.didMoveToParentViewController(self)

Check my Swift Github Sample Code

Objective-C

Create your own custom container view controller (I will call it combinedViewController), which will hold your three controllers in scroll view.
Inherit like you always do UIViewController, then use addChildViewController public API in your new combinedViewController -viewDidLoad: like this:

[self addChildViewController:aViewController];
[self.scrollView addSubview:aViewController.view];
[aViewController didMoveToParentViewController:self];

Here’s what the code does:

  • It calls the container’s addChildViewController: method to add the child.
  • It accesses the child’s view property to retrieve the view and adds it to its own view hierarchy. The container sets the child’s size and position before adding the view; containers always choose where the child’s content appears.
  • It explicitly calls the child’s didMoveToParentViewController: method to signal that the operation is complete.

Do this operation with each of your viewControllers. Afterwards, set your combinedViewController as a rootViewController.

if you need further explanation, feel free to ask.

Reference: Design custom container view controller

Here you are my Objective-C Github sample code

UPD: Thanks @Oliver Atkinson for clarifying that addChildViewController: method also calls the child’s willMoveToParentViewController: method automatically.

Results:

enter image description here

Leave a Comment