UIPageViewController: get the currentPage

后端 未结 12 684
别那么骄傲
别那么骄傲 2021-02-03 22:22

I have been struggling with this issue for the last few days and after all this juggling I have figured out that all I need is the current Index from the datasource method to up

12条回答
  •  长情又很酷
    2021-02-03 22:50

    I have solved this problem like this:

    * Parent View Controller (PageViewController) *

    @interface MyParentPageViewController () 
    
    
    @property (nonatomic, assign) NSUInteger currentPageIndex;
    
    @end
    
    @implementation MyParentPageViewController
    
    - (void)viewDidLoad 
    {
      [super viewDidLoad];
    
      MyChildViewController *rootChildViewController = [MyChildViewController controllerWithPageIndex:self.currentPageIndex];
      [self setViewControllers:@[rootChildViewController]
                 direction:UIPageViewControllerNavigationDirectionForward
                  animated:YES completion:nil];
      self.dataSource = self;
    }
    
    #pragma mark - Page View Controller DataSource
    - (UIViewController *)pageViewController:(UIPageViewController *)pageViewController 
    viewControllerAfterViewController:(MyChildViewController *)viewController
    {
      if (viewController.pageIndex == self.sourceArray.count - 1) {
        return nil;
      }
      MyChildViewController *vc = [MyChildViewController controllerWithPageIndex:viewController.pageIndex + 1];
      return vc;
    }
    
    - (UIViewController *)pageViewController:(UIPageViewController *)pageViewController
    viewControllerBeforeViewController:(CHHomeDetailTableController *)viewController 
    {
      if (viewController.pageIndex == 0) {
        return nil;
      }
      MyChilViewController *vc = [MyChildViewController controllerWithPageIndex:viewController.pageIndex - 1];
      return vc;
    }
    
    
    @end
    

    * Child View Controller *

    @implementation MyChildViewController
    - (void)viewWillAppear
    {
        MyParentPageViewController *parentPageViewController = (MyParentPageViewController *)self.parentViewController;
        parentViewController.currentPageIndex = self.pageIndex;
    }
    @end
    

    For example, the parentPageViewController's currentPageIndex is 10 , or some other values, when your swipe right, parentViewController.currentPageIndex will be 9, if 0 , nothing happened; If you swipe left, parentPageViewController.currentPageIndex will be 11, if the showing controller.view is the last, nothing happened too.

提交回复
热议问题