UIPageViewController viewControllerAfterViewContro

2020-06-21 04:49发布

问题:

I'm trying to implement UIPageViewController with validation on every step. My code was working fine without validation, so everything with pages seems to be done right. This is my code:

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
    int index = [(MyViewController *) viewController index];
    index--;
    return [_viewModel viewControllerAtIndex:index];
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {
    BOOL isDataValid = [(MyViewController *) viewController validateData];
    if (isDataValid) {
        int index = [(MyViewController *) viewController index];
        index++;
        return [_viewModel viewControllerAtIndex:index];
    }
    return nil;
}

My problem is that when step 1 is shown, viewControllerAfterViewController is called to prepare step 2, but because step 2 cannot be valid (user didn't have chance to input data) so it is returning nil. I would like UIPageViewController to call viewControllerAfterViewController every time user tries to swipe to the next screen and not give up after receiving a nil. Is it doable?

回答1:

UIPageViewController has an underlying cache. You can reset it with

pageViewController.dataSource = nil;
pageViewController.dataSource = self;

You can call this once the page you are on becomes valid.



回答2:

Faced similar issue, I added the following code (Only calling add subview is not enough)

[self addChildViewController:vc];
[_viewCarouselContainer addSubview:vc.view];
[vc didMoveToParentViewController:self];

Now both methods are getting called properly on respective swipes

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController ;

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController ;