Search code examples
iosuiviewcontrolleruiscrollviewuistoryboarduipagecontrol

iOS - load and switch between pages using UIPageContol


I would like to use UIPageControl to navigate between different view controllers. I have 2 view controllers and another main view controller contains the UIPageControl. The 2 view controllers to be navigated between have been added as children to the main view controller. When I currently start the application, I see a blank screen. I used pageControl.currentPage = 0 but I am unable to understand why I am unable to see the views.

Note that I do not want to use UIScrollView in my application.

Edit - I have followed this tutorial http://www.wannabegeek.com/?p=168

But it uses scroll view. I do not want to use scroll view since it is creating some issues with a UIWebView and a CorePlot which I use in the different view controllers.

I seek guidance as to how to modify this tutorial without using scroll view. Thanks!


Solution

  • Adding the other view controllers as children just associates the view controllers - it doesn't add the views they manage as subviews. So, when you add them as children you should also add the subviews and set the initial frames. You might also want to add swipe gestures to trigger view animations to animate the frames of the views (though there are several other options, like using a scroll view).

    As part of the animation to move the views you manually update the page control (that won't happen automatically).


    The loadScrollViewWithPage method is the key. Call this with parameter 0 and then 1 to load both of the pages and add the views as subviews. Just change self.scrollView to self.view.

    I would add a (two really, but get 1 working first) swipe gesture to the page control. Then when it is swiped you can move the other views.

    The swipe gesture callback:

    - (void)swipeRightToLeftGesture:(UIGestureRecognizer *)gestureRecognizer
    {
        [UIView animateWithDuration:1
                         animations:^{
    
                         for (UIViewController *vc in self.childViewControllers) {
                             CGRect frame = vc.view.frame;
                             frame.origin.x -= self.view.frame.size.width;
                             vc.view.frame = frame;
                         }
                     }];
    }
    

    This iterations over the child view controllers and animates the frames of their views to move them to the left. The swipe left to right handler will be the same except it will += the width to move the to the right.

    [Code Edited - syntax]