Search code examples
iosobjective-cbuttonuipageviewcontroller

Next Page Button for UIPageViewController iOS 8 - objC


Actually I'm trying to populate gallery using PageViewController. I brought scrolling images in a view successfully but, I used Next and Previous button in page View Controller its not working properly i used this line of code.

- (IBAction)previousButtonPressed:(id)sender {
    PageContentViewController *startingViewController = [self viewControllerAtIndex:0];
    NSArray *viewControllers = @[startingViewController];
    [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionReverse animated:NO completion:nil];
}

- (IBAction)nextButtonPressed:(id)sender {
    PageContentViewController *startingViewController = [self viewControllerAtIndex:+1];
    NSArray *viewControllers = @[startingViewController];
    [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
    }

Since I used viewControllerAtIndex:+1 at the - (IBAction)nextButtonPressed:(id)sender Im getting the button action working only for first click of a button action. Thanks in advance


Solution

  • Check this Code :-

    - (void)changePage:(UIPageViewControllerNavigationDirection)direction {
        NSUInteger pageIndex = ((FooViewController *) [_pageViewController.viewControllers objectAtIndex:0]).pageIndex;
        if (direction == UIPageViewControllerNavigationDirectionForward){
            pageIndex++;
        }else {
            pageIndex--;
        }
        YourViewController *viewController = [self  viewControllerAtIndex:pageIndex];
        if (viewController == nil) {
            return;
        }
        [_pageViewController setViewControllers:@[viewController] direction:direction animated:YES completion:nil];
    }
    

    // Previous Button

    - (IBAction)previousButtonPressed:(id)sender {
        [self changePage:UIPageViewControllerNavigationDirectionReverse];
    }
    

    // Next Button

    - (IBAction)nextButtonPressed:(id)sender {
        [self changePage:UIPageViewControllerNavigationDirectionForward];
    }