Search code examples
iosuipageviewcontroller

Is there way to get all the pre-loaded view controllers in UIPageViewController


I have an UIPageViewController. I can flip the pages and everything works fine. The UIPageViewController pre-loads one ViewController. At this point, there are two view controllers in memory (one is the visible controller while another is the pre-loaded controller). I want to get the two ViewControllers so that I could change some settings on the fly.

The question is how could I get the pre-loaded child view controllers? If I cannot get those controllers, what is the best way to reset some properties on all the preloaded view controllers?


Solution

  • You can modify your custom object which can be used to build your view controller:

    - (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
        NSUInteger index = [(PageChildViewController *) viewController index];
        if (index == 0) {
            return nil;
        }
        index--;
        return [self viewControllerAtIndex:index];
    }
    
    - (UIViewController *)viewControllerAtIndex:(NSUInteger)index {
        CustomObject *customObject = self.customObjects[index];
        PageChildViewController *childViewController = [PageChildViewController controllerWithIndex:index andCustomObject:customObject];
        return childViewController;
    }
    
    - (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {
        NSUInteger index = [(PageChildViewController *) viewController index];
        index++;
        if (index == self.pages.count) {
            return nil;
        }
        return [self viewControllerAtIndex:index];
    }
    

    If you need to update currently visible page view controller you can use this:

    [self.pageController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
    

    If you need to reset you page view controller cache you can use this:

    self.pageController.dataSource = nil;
    self.pageController.dataSource = self;