1

I am trying to implement a UIPageViewController. I have done this before but using the same UIViewController and changing the images etc when paging. I want to page between different UIViewController now. I'm trying to code the method that creates the UIViewController based on what is in an array that contains the storyboard ID for the UIViewControllers. For example I have this array:

self.controllerIdentifiers=[NSArray arrayWithObjects:@"ViewControllerTypeA",@"ViewControllerTypeB", nil];

Now trying to implement :

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController
{
    if (self.controllerIndex==0) return nil;

    self.controllerIndex--;
    NSString *id = self.controllerIdentifiers[self.controllerIndex];

    //If I knew the controller type I would do something like this..

    ViewControllerTypeA *typeA = [self.storyboard instantiateViewControllerWithIdentifier:@"ViewControllerTypeA"];

    return typeA;
}

The problem is I'm not sure how to tell the code what type of UIViewController it is. Do I need to case some logic for every possible index and just initiate a UIViewController that way?

1

1 Answer 1

2

I use this template to achieve this. It comes from a (possible duplicate) question with two interesting answers that you can find there.

EDIT:
TL;DR the idea is to use storyboard identifiers for your different view controllers to instantiate them when needed, using the PageViewControllerDataSource protocol methods.

7
  • Hey, just took a look at this github example. It seems that all the UIViewControllers in this are of the class UIViewController. My UIViewControllers are all different types i.e use different class files so I'm not sure how to initiate it if i don't know its type.
    – Kex
    May 25, 2015 at 13:54
  • It doesn't matter. Since it's instantiated from a storyboard, iOS will do the work for you. The root viewController doesn't need to be aware of the different page classes. May 25, 2015 at 13:56
  • would I initiate it with UIViewController *controller = [self.storyboard instantiateViewControllerWithIdentifier:@"SomeID"]; then?
    – Kex
    May 25, 2015 at 13:58
  • Have a look at BaseContentViewController. He subclasses all his pages from it. May 25, 2015 at 14:01
  • Yeah, see that. Just don't get why you don't have to cast the UIViewController or anything. e.g we have UIViewController *previousViewController = [self viewControllerAtIndex:index - 1]; but the previous view controller may be a Page2ViewController class..
    – Kex
    May 25, 2015 at 14:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.