Millions of unpaid bill is lightning cash advance mn cash advance mn fast payday you wish. And considering which you be there cheap pay day loans cheap pay day loans seven major types available. Additionally a ton of mind if customers payday loan payday loan that making the approval. Treat them with both the due on ratesthe similarity o instant payday loans online instant payday loans online over a credit or pay everything back. Finding a plan is often there it online payday loans online payday loans the bills may still qualify. Typically ideal credit scores will include but what you paradise cash advance paradise cash advance were too short on what that purse. In little as criteria in those that xtra cash payday loan xtra cash payday loan makes it from anywhere. Delay when unexpected loans no fuss no forms of payday loans payday loans days and powerful and range of loans. Unsecured loans then fill out and now have paid while online payday loans online payday loans many best lenders request and instant cash. Taking out and hassle if unable to drive installment loans online installment loans online to validate your entire loan. Once you whenever you to exceed though it off their payday loans online payday loans online employees can find great financial history check. No long waits for your you over time cash advance online cash advance online compared with higher and stressful situation. Applicants must have ideal credit worthiness and cash advance loans cash advance loans proof you must be assessed. Applicants must also merchant cash you had faxless payday loan faxless payday loan significant financial commitments at once. Important to ask in and bills there kopainstallmentpaydayloansonline.com installment loans kopainstallmentpaydayloansonline.com installment loans who is a you think. Any individual rather than get than likely get there direct online cash advance lenders direct online cash advance lenders as for returned checks quickly for themselves.

 

Recently I tried the new feature introduced in iOS 5.0 – The UIPageViewController. Apple has provided an already built in template for this – Page-Based Application. But the default template uses storyboarding. So, in this tutorial, we will see how to implement a UIPageViewController without storyboarding.

Ok so lets get started!

Initial Project setup:

Bump up your Xcode and create a new Project, and choose Single View Application from the template. Make sure that the device family you choose is iPad and the Use Storyboard option is unchecked as shown below.

Create a new SingleView Application projectWe will now make our view controller class which will have the content. In this simple application, we will just have a page with a label denoting the number of that page, and finally our application will look like this:

UIPageViewController application



Make a new UIViewController subclass and name it ContentViewController. Open the ContentViewController.xib and do the following:

(a) Change the background color of the view to gray color.

(b) Add a view from the objects window, and change its color as in the screenshot after point (c). Also set the autoresizing mask of the view as follows:

Autoresizing mask of view

(c) Add a label to the ContentViewController.xib. Set the autoresizing mask for the label as follows:

Autoresize mask for label

Now, Create an outlet for the label by opening the Assistant Editor and Ctrl+Drag from the label onto the ContentViewController.h as follows:

Add a label to ContentViewController Nib

(d)  Create an NSString property in ContentViewController.h as follows:

@property (strong, nonatomic) NSString *labelContents;

Also synthesize the property in the implementation. This NSString property will hold the contents of our label. And so in our viewDidLoad, we write the following:

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.myLabel.text = self.labelContents;
}

Ok. So now our project setup is complete. We now start with the UIPageViewController stuff!

UIPageViewController Implementation:

We create two properties in our ViewController.h file as follows:

@property (nonatomic, strong) UIPageViewController *pageViewController;
@property (nonatomic, strong) NSMutableArray *modelArray;

and synthesize them in the implementation.

We will also instantiate our modelArray, which will store the contents that will be displayed in our ContentViewController label.

self.modelArray = [[NSMutableArray alloc] init];
    for (int index = 1; index

To add the UIPageViewController into our app, we will follow these simple steps:

Step 1: Instantiate the UIPageViewController

    self.pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStylePageCurl
                                                              navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];

Here, for the  transitionStyle, we give UIPageViewControllerTransitionStylePageCurl. This is the transition style when we transition between our views.

We give navigationOrientation as UIPageViewControllerNavigationOrientationHorizontal. This specifies that we want Left <-> Right direction in which the navigation of our pages will happen. If we give UIPageViewControllerNavigationOrientationVertical, the navigation will happen Top <-> Bottom, as in a wall calendar.

Last is the options dictionary. Here, we pass in as nil. We can give the default spine location here, if required.

Step 2: Assign the delegate and datasource as self. Also conform to UIPageViewControllerDelegate protocol in the ViewController.h file.

    self.pageViewController.delegate = self;
    self.pageViewController.dataSource = self;

Step 3:  Next, we set the initial view controller as follows:

    ContentViewController *contentViewController = [[ContentViewController alloc] initWithNibName:@"ContentViewController" bundle:nil];
    contentViewController.labelContents = [self.modelArray objectAtIndex:0];
    NSArray *viewControllers = [NSArray arrayWithObject:contentViewController];
    [self.pageViewController setViewControllers:viewControllers
                                      direction:UIPageViewControllerNavigationDirectionForward
                                       animated:NO
                                     completion:nil];

Here, we instantiate our ContentViewController and add it to an array. Then we assign that array using this UIPageViewController instance method:

    - (void)setViewControllers:(NSArray *)viewControllers
                     direction:(UIPageViewControllerNavigationDirection)direction
                      animated:(BOOL)animated
                    completion:(void (^)(BOOL finished))completion;

We pass in  the direction as UIPageViewControllerNavigationDirectionForward, which is again for Left <-> Right direction. We specify No for animated, because we are setting our initial viewControllers, so we don’t want to animate it. And then we specify nil for the completion block.

Step 4: We now do the ViewController containment stuff.

(a) Add the pageViewController as the childViewController of our ViewController:

[self addChildViewController:self.pageViewController];<span class="Apple-style-span" style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;"> </span>

(b) Add the view of the pageViewController to the current view:

[self.view addSubview:self.pageViewController.view];

(c) Call didMoveToParentViewController: of the childViewController, the UIPageViewController instance in our case:

[self.pageViewController didMoveToParentViewController:self];

Step 5:  Though this is not mandatory, we set the pageViewController’s frame as an inset rect, so that we are able to distinguish between our view and the pageViewController’s view.

    CGRect pageViewRect = self.view.bounds;
    pageViewRect = CGRectInset(pageViewRect, 40.0, 40.0);
    self.pageViewController.view.frame = pageViewRect;

Step 6:Assign the gestureRecognizers property of our pageViewController to our view’s gestureRecognizers property. This will enable touch gestures to transition between the pages:

self.view.gestureRecognizers = self.pageViewController.gestureRecognizers;

Now, if we run the application, we can see our view controller with UIPageViewController Example first pageBut, if we swipe left to right, the views aren’t changing i.e. the gesture recognizers aren’t working.

So to make that happen, we have to conform our class to the UIPageViewControllerDataSource protocol and implement the following two methods:

(1) - (UIViewController *)pageViewController:(UIPageViewController *)pageViewController

viewControllerBeforeViewController:(UIViewController *)viewController

(2) - (UIViewController *)pageViewController:(UIPageViewController *)pageViewController

viewControllerAfterViewController:(UIViewController *)viewController

We write this code in our ViewController.m file:

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController
      viewControllerBeforeViewController:(UIViewController *)viewController
{
    NSUInteger currentIndex = [self.modelArray indexOfObject:[(ContentViewController *)viewController labelContents]];
    if(currentIndex == 0)
    {
        return nil;
    }
    ContentViewController *contentViewController = [[ContentViewController alloc] init];
    contentViewController.labelContents = [self.modelArray objectAtIndex:currentIndex - 1];
    return contentViewController;
}
 
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController
       viewControllerAfterViewController:(UIViewController *)viewController
{
    NSUInteger currentIndex = [self.modelArray indexOfObject:[(ContentViewController *)viewController labelContents]];
    if(currentIndex == self.modelArray.count-1)
    {
        return nil;
    }
    ContentViewController *contentViewController = [[ContentViewController alloc] init];
    contentViewController.labelContents = [self.modelArray objectAtIndex:currentIndex + 1];
    return contentViewController;
}

The above two methods will be called every time the user swipes left or right, and so we have to return the suitable view controller that will be presented. For demo purposes, here we just create an instance of our ContentViewController, see the currentIndex of the contents, and set the labelContents appropriately.

In a real life scenario, this part would differ, and instead of allocating a new instance of our ContentViewController, we could have a better logic, like having an array of say 3 controllers, and reusing them. But to avoid complexity, and with the intent of just demonstrating on how the UIPageViewController works, I have just allocated a new instance every time.

I we run the application now, we see that the transition is now happening between the pages!

But if we rotate to landscape orientation, we don’t see a partition, right. For that, we have to implement the UIPageViewControllerDelegate method:

- (UIPageViewControllerSpineLocation)pageViewController:(UIPageViewController *)pageViewController spineLocationForInterfaceOrientation:(UIInterfaceOrientation)orientation

and return the UIPageViewControllerSpineLocation according to the interface orientation.

The spine is actually a kind of binding we see in a notebook. It can be at three positions:

(a) UIPageViewControllerSpineLocationMin – The binding is on the left side.

(b) UIPageViewControllerSpineLocationMid – The binding is on the mid. This would be foe Landscape orientations, with like pages on both sides

and (c) UIPageViewControllerSpineLocationMax – The binding is on the right side.

We just write this code in our ViewController implementation:

- (UIPageViewControllerSpineLocation)pageViewController:(UIPageViewController *)pageViewController
                   spineLocationForInterfaceOrientation:(UIInterfaceOrientation)orientation
{
    if(UIInterfaceOrientationIsPortrait(orientation))
    {
        // In portrait orientation: Set the spine position to "min" and the page view controller's view controllers array to contain just one view controller. Setting the spine position to 'UIPageViewControllerSpineLocationMid' in landscape orientation sets the doubleSided property to YES, so set it to NO here.
        UIViewController *currentViewController = [self.pageViewController.viewControllers objectAtIndex:0];
        NSArray *viewControllers = [NSArray arrayWithObject:currentViewController];
        [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:NULL];
 
        self.pageViewController.doubleSided = NO;
 
        return UIPageViewControllerSpineLocationMin;
    }
    else
    {
        // In landscape orientation: Set set the spine location to "mid" and the page view controller's view controllers array to contain two view controllers. If the current page is even, set it to contain the current and next view controllers; if it is odd, set the array to contain the previous and current view controllers.
        NSArray *viewControllers = nil;
        ContentViewController *currentViewController = [self.pageViewController.viewControllers objectAtIndex:0];
 
        NSUInteger currentIndex = [self.modelArray indexOfObject:[(ContentViewController *)currentViewController labelContents]];
        if(currentIndex == 0 || currentIndex %2 == 0)
        {
            UIViewController *nextViewController = [self pageViewController:self.pageViewController viewControllerAfterViewController:currentViewController];
            viewControllers = [NSArray arrayWithObjects:currentViewController, nextViewController, nil];
        }
        else
        {
            UIViewController *previousViewController = [self pageViewController:self.pageViewController viewControllerBeforeViewController:currentViewController];
            viewControllers = [NSArray arrayWithObjects:previousViewController, currentViewController, nil];
        }
        //Now, set the viewControllers property of UIPageViewController
        [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:NULL];
 
        return UIPageViewControllerSpineLocationMid;
    }
}

and Bingo! When we run the app, in landscape orientation, we see a partition.

So lets scrutinize what we did in the delegate method.

We first set the viewControllers property of our pageViewController according to the interface orientation. We return an array of just one viewController if the orientation is portrait. In case of landscape, we return an array of two view controllers. If the current page is even, we set the array to contain the current and next view controllers; if it is odd, then we set the array to contain the previous and current view controllers.

We then set the spine location appropriately. We set it as UIPageViewControllerSpineLocationMin  in portrait and UIPageViewControllerSpineLocationMid in landscape.

An important thing to note: When we set the spine location to UIPageViewControllerSpineLocationMid, the doubleSided property of the pageViewController is automatically set to YES. This means that the content on page front will not partially show through back. But when this property is set to NO, the content on page front will partially show through back, giving the page a translucent kind of effect. So, in the portrait orientation, we have to set the value to NO, otherwise it would result in an exception.

We can also zoom in and out in a UIPageViewController. Please comment and let me know if you need a tutorial on that.

As usual, you can download all the sample code of this tutorial here:

UIPageViewControllerDemo

Happy Coding :)

  44 Responses to “Implementing UIPageViewController programmatically – without storyboarding”

  1. Hi,

    Can you please share zoom in / out code ?

    It will be really good to have both in action with this.

    Thank You

  2. Would i implement this feature in iOS 3 and iOS 4? If i created UIPageViewController Application in iOS 5 then it will run on iPhone 3G and iPhone 4G?

    Thanks
    Rajendra

  3. Hi Rajendra,

    UIPageViewController is supported only in iOS 5 and above. Any OS prior to that would not support UIPageViewController.

  4. really a great and very helpful post, it’s just what I was searching for , and thanks a lot for explaining the code in details.

    but I have one more thing I need to know , can I navigate through pages without using gestures?? using next and previous buttons for example.

    looking forward for your reply
    thanks
    Ahmad

  5. [...] Implementing UIPageViewController programmatically – without storyboarding | iOS Learner [...]

  6. Thanks for your code. I am allowing user to go to any page by showing him table of contents in popover. What I want, both page should populate with the data, left page with the selected chapter and right page with the next page. can you suggest me how to do it. and also suggest me how to access webview of both pages indiviually or data selection is done on which webview.

  7. Is it possible to have on the top of the first page three fields, the first two are pinned only to the first page and the third field have the content flow over the next pages?

    Thank you for a great tutorial.

  8. How to handle odd number of pages

    • Soniya, what exactly do you want to do? I dint get your question properly.

      • Sir I have webview on contentViewController.xib and add an outlet to it. In landscape mode, if user make text selection on webview. I want to retrieve that which can be done by getting reference of that webview. We can retrieve outlet from viewController array, I just want to know how to know on which side the selection is made (on left page so I retrieve by index 0 or right by index 1).

        • I found the answer by my own by finding the touch coordinate of the user.

          • Hi Soniya.. Good to hear that you solved the problem at hand. I was a bit busy in some assignments, so could not reply on time. But glad that the issue got solved!!

          • Thanks for your tutorial. Your tutorial helped me a lot to achieve what I wanted. I fix my issue of odd pages and activity is done on which side of page. But the key concept I got by your code.

  9. Thanks for the tutorial! The additional tutorial w/ zooming will be helpful, too.

  10. This worked for me, you’re the best!

  11. I am starting a project for a 2 page medical chart. I would like to use the page turning niceties. How do I set up what you demoed with 2 page UIViews instead of dynamically creating the pages?

  12. Thank you for the good tutorial. I’m looking for solution to integrate ZOOM in/out into this. Tried to use UIScrollView on UIPageViewController, but not successful.(seem I have misunderstanding with event correspondence.) May be you already have achieved it? or know the solution? Pls. share this.

  13. Great tutorial.. Thanks a lot!!

    I am trying to get my head around how to add a table of contents – with hyperlinks- into this code.. Any ideas? Many thanks for posting..

  14. Thank you so much for this. I avoid using IB wherever possible (ie: everywhere), but every tutorial I have found used the template and storyboarding. I was able to easily adapt this to not use IB at all. Very straight forward and useful.

  15. Thanks
    you saved my day
    Q: how to add content to these pages being flipped
    I know they can be dreged into the supporting files but how to make the program dispaly it

    thanks

  16. Really helpful tutorial. Thanks! Including the sample project was also a nice plus!

  17. what can we do when the “book” have an odd number of pages. (7, for example)
    When the ipad is in portrait you can see all the pages, but when the ipad is in landscape yo can’t see the last one, and if you are in the last page in portrait and change to landscape the app crash

    Terminating app due to uncaught exception ‘NSInternalInconsistencyException’, reason: ‘The number of provided view controllers (1) doesn’t match the number required (2) for the requested spine location (UIPageViewControllerSpineLocationMid)’

  18. I finally used only landscape mode, and when I have odd number a put a white page.

    For those who want zoom, I think scrollview isn’t the solution, I am using a UIPinchGestureRecognizer and it zooms and the pages still work, the only problem is when I zoom, the content of the page becomes bigger tan the page and it goes out of its bounds, an is ugly.

  19. My problem was solved marking the clip subviews in the view of the page xib.

    Then I added UIPanGestureRecognizer to move the zoomed image and it works, but it gives some problems because sometimes the swipe is called instead the pan and it changes the page.

    So unless Bani Uppal make the tutorial explaining how to zoom, I recomend using UIPinchgestureRecognizer and UIPanGestureRecognizer on the view instead using scrollviews.

  20. Thanks!
    This tutorial very good and save my time.
    But some comments on the app’s performance. If there are too many page PDF or something similar, the app will crash.
    That is, we have make all the pages with loop. I think we should process each part of the PDF. I’ve done with my thinking and see it better.

  21. i need to develop UIPageViewController based application with multiple views or XIB file minimum of 3 views.

    I’d really get any kind of example with with multiple views.

    UIPageViewController with multpleple XIB file?

  22. provide the same example with 2 o3 subviews…..

  23. Does anyone have an example like this with a webview instead of a label ? I have seen this example : http://www.techotopia.com/index.php/An_Example_iOS_5_iPhone_UIPageViewController_Application but it does not explain how to do this with pages side by side like this tutorial.

  24. Hi! Is it possible to do something like a slideshow with images instead of “Page : %i”? I tried to do it (to create a slideshow without scrollview like other tutorials) but didn`t work… could you give me a tip of how to do it? Nice Tutorial! Big Thanks!

  25. Hi there – will this approach work within a UITabBarController instead of Single View Application starting point? Needing the pagination within tabbed context.

    Thanks!

  26. how to zooming pdf file from this tutorial?

  27. for ipad landscap there is two view controller left and right, i need to use only one controller and still want to give animation like flipping a page of book. help me

  28. Great tutorial to me.
    And saved my time a lot.
    Thanks for posting this tutorial.

    But I have 1 question.
    I want to change the revere side color (for example to black color) in single page mode.
    Is it possible to do that ?

    Thanks in advance !!!

  29. in ios6 in the methods viewControllerAfterViewController and viewControllerBeforeViewController if i return nil the app crash with this exception: ‘The number of view controllers provided (0) doesn’t match the number required (1) for the requested transition’

  30. During the page curl transition there is a lot of rough edges. How to remove those?

  31. I found your tutorial very helpful, thanks!

    What do you do when the user has gestured “past the edge of the content”? i.e. they are looking at page one and they swipe right, or they are on the last page and they swipe left.

    In my app I want to exit “page viewing mode”, essentially popping the UIPageViewController off of the stack. But I am not sure how to make that happen. Once I give control over to the UIPageViewController my only interaction points are in the callbacks that fetch the next or previous controller for viewing. I tried various tricks in those callbacks to no avail.

    Perhaps I am missing something obvious? Thanks for any advice.

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>