Swift - UIPageViewController always repeats second ViewController

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-06 01:07:30

I've had a very similar problem (not using swift, in obj-c, had 3 view controllers and the one in the middle repeated one time: "0,1,1,2"). Turned out it was all about the Page View Controller Data Source methods...

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

I haven't really digged into swift (nor had the interest in doing so yet), but pseudo-reading your code leaves me the idea that you restrict the limits of the "before" and "after" key methods (swift-wise) with variables contained inside the controller used as the UIPageViewControllerDataSource, that is exactly what I changed and fixed the issue.

I don't have the best english but I hope you understood that last statement. The fix I used was based on this tutorial. In my case, the view controllers I used in all 3 cases where "UINavigationViewControllers", so I created a "NavigationWrapperViewController" that had a property:

@property(assign, nonatomic) NSUInteger index;

Then, when checking for the boundary limits in the key Data Source methods did (only showing one, use the same technique for the other one):

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
   NSUInteger indice = ((NavigationWrapperViewController*)viewController).index;
   if ((indice == 0) || (indice == NSNotFound)) {
       return nil;
   }    
   return [self viewControllerAtIndex:(--indice)];
}

And when instantiating view controllers in viewControllerAtIndex, don't forget to set that property correctly before returning them:

NavigationWrapperViewController *wrapperViewController = [self.storyboard instantiateViewControllerWithIdentifier:self.ViewControllers[index]];
wrapperViewController.index = index;

return wrapperViewController;

The subtle difference is that the index of the view controller displayed is stored by the current view controller (using a simple wrapper, that class was made entirely with that purpose, it just has a property implementation in his .h file) instead of the UIPageViewControllerDataSource responsible class.

That fixed my problem, maybe it was some sort of thread related issue that influenced on the current view controller index that was fetched and that caused the whole - repeating view controllers - problem.

Hope it helps if you are willing to try it out!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!