Collin Schupman Collin Schupman - 1 year ago 147
iOS Question

iOS: UIPageViewController - Use button to jump to next page

I have a series of VCs in a PageViewController that a user navigates left to right through with their fingers. I need to add in buttons that essentially perform the same action as the finger swiping, moving left or right by one through the VCs . How can I do this? Right now I am using these two methods to dynamically setting the VCs as the user swipes:

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

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

Is there someway I can do the same thing if a user clicks a button?

Answer Source

You can programmatically set the currently displayed view controller with a transition animation using setViewControllers:direction:animated:completion: on your page view controller.

Here is an example that presents view controllers with random background colors. You can adjust this to use your specific view controllers.

- (void)viewDidLoad
    [super viewDidLoad];
    self.pvc = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
    self.pvc.view.frame = CGRectInset(self.view.bounds, 200, 200);
    [self.view addSubview:self.pvc.view];

    [self.pvc setViewControllers:@[[self randomVC]] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil];

    UIViewController *vc = [[UIViewController alloc] init];
    UIColor *color = [UIColor colorWithRed:arc4random_uniform(255)/255.0 green:arc4random_uniform(255)/255.0 blue:arc4random_uniform(255)/255.0 alpha:1];
    vc.view.backgroundColor = color;
    return vc;

- (IBAction)previousButtonPressed:(id)sender {
    [self.pvc setViewControllers:@[[self randomVC]] direction:UIPageViewControllerNavigationDirectionReverse animated:YES completion:nil];

- (IBAction)nextButtonPressed:(id)sender {
    [self.pvc setViewControllers:@[[self randomVC]] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download