Dpak Dpak - 3 months ago 25
iOS Question

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

Answer

Objective c Code :-

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

Swift Code : -

func changePage(direction: UIPageViewControllerNavigationDirection) {
    var pageIndex: Int = (pageViewController.viewControllers[0] as! FooViewController).pageIndex
    if direction == .Forward {
        pageIndex += 1
    }
    else {
        pageIndex -= 1
    }
    var viewController: FooViewController = self.viewControllerAtIndex(pageIndex)
    if viewController == nil {
        return
    }
    pageViewController.setViewControllers([viewController], direction: direction, animated: true, completion: { _ in })
}

@IBAction func previousButtonPressed(sender: AnyObject) {
    self.changePage(.Reverse)
}

@IBAction func nextButtonPressed(sender: AnyObject) {
    self.changePage(.Forward)
}