IOS 5: A uipageviewcontroller program example

Source: Internet
Author: User

Original article: http://www.techotopia.com/index.php/An_Example_iOS_5_iPhone_UIPageViewController_Application

When creating a project in xcode, you can select the "Page-based application" Project template. You can use this template to create a "Page-based" application that displays different pages every month of the year. Strangely, this is the only instance-based template provided by xcode, rather than the basic application framework. This is useful for learning from the beginning, but unless you really need a program that uses 12 pages to display different months of the year, you must remove some existing items from this template, for other purposes.

In fact, apart from using xcode's "Page-based application" template, we can also use the single view application template, but we only need to implement page-based behavior. There are two benefits. First, without using the page-base template, we can better understand the Implementation Details of uipageviewcontroller. This method is simpler than modifying the page-based application template.

Create a project

Start xcode and create an iOS single view application project. Make sure you do not use the use storyboard option.

Create contentviewcontroller

This example uses a single view controller instance to display multiple pages. The view contains a uiwebview that displays different HTML content based on the selected page. The viewcontroller class has a Data Object attribute used to hold the HTML of the view.

Select File à New à newfile... Menu, create uiviewcontroller subclass, named contentviewcontroller (check "with XIB ..." Option ). Open contentviewcontroller. H, add an exit for the webview object and data object, and connect them.

#import <UIKit/UIKit.h>
@interface contentViewController : UIViewController 
@property (strong, nonatomic) IBOutlet UIWebView *webView; 
@property (strong, nonatomic) id dataObject; 
@end 

Open contentviewcontroller. XIB and drag a uiwebview component to the View:

Right-click the file's owner, drag a connection line to the Web View object, and select webview exit.

Edit the contentviewcontroller. M file. Every time you flip a page, the data source method of uipageviewcontroller creates a new contentviewcontroller instance and sets its dataobject attribute to the corresponding HTML. In the viewwillappear method of contentviewcontroller, The dataobject attribute is assigned to the webview object. To this end, we have added the necessary @ synthesize statement and modified the viewwillappear method:

#import "contentViewController.h"  
@implementation contentViewController 
@synthesize webView, dataObject; 
. 
. 
- (void)viewWillAppear:(BOOL)animated {
     [super viewWillAppear:animated];
     [webView loadHTMLString:dataObject
         baseURL:[NSURL URLWithString:@""]]; 
} 
. 
. 
@end 

Next, we will implement the data model.

Create a data model

The data model in this example is a string array. Each string contains different HTML content. The pageappviewcontroller class is the data source of the uipageviewcontroller object. This class contains an nsarry and a uipageviewcontroller object, and implements the uipageviewcontrollerdatasource protocol at the same time. Open pageappviewcontroller. H, import the contentviewcontroller. h header file, and add the necessary declaration:

 

#import <UIKit/UIKit.h> 
#import “contentViewController.h”  
@interface pageAppViewController : UIViewController <UIPageViewControllerDataSource> {
     UIPageViewController *pageController;
     NSArray *pageContent; 
} 
@property (strong, nonatomic) UIPageViewController *pageController; 
@property (strong, nonatomic) NSArray *pageContent; 
@end 

Finally, add a method in pageappviewcontroller. m to add the HTML string to the array. Call this method in the viewdidload method.

 
#import "pageAppViewController.h"  
@implementation pageAppViewController 
@synthesize pageController, pageContent;
 .
 . 
- (void) createContentPages {
     NSMutableArray *pageStrings = [[NSMutableArray alloc] init];
     for (int i = 1; i < 11; i++)
     {
         NSString *contentString = [[NSString alloc]
 initWithFormat:@"
         [pageStrings addObject:contentString];
     }
     pageContent = [[NSArray alloc] initWithArray:pageStrings]; 
}
 .
 . 
- (void)viewDidLoad {
     [super viewDidLoad];
     [self createContentPages]; 
} 
 

Now we have a content View Controller and a data model. The data model extracts the content of each page through the data source method. The next step is to implement these data source methods. As described in "implementinga page based iOS 5 iPhone application using uipageviewcontroller", the uipageviewcontroller instance requires a data source. There are two data source methods. One is to return the View Controller after the currently displayed view controller, the other is to return the viewcontroller before the currently displayed view controller. Since pageappviewcontroller acts as the data source of Page View Controller, you need to add these two methods (and the other two convenient methods) to pageappviewcontroller. M ). First, let's look at these two convenient methods:

 

#import "pageAppViewController.h"  
@implementation pageAppViewController 
@synthesize pageController, pageContent;  
- (contentViewController *)viewControllerAtIndex:(NSUInteger)index {
     // Return the data view controller for the given index.
     if (([self.pageContent count] == 0) || 
             (index >= [self.pageContent count])) {
         return nil;
     }
      // Create a new view controller and pass suitable data.
     contentViewController *dataViewController = 
         [[contentViewController alloc]
         initWithNibName:@"contentViewController" 
         bundle:nil];
     dataViewController.dataObject =
        [self.pageContent objectAtIndex:index];
     return dataViewController; 
- (NSUInteger)indexOfViewController:(contentViewController *)viewController {
      return [self.pageContent 
indexOfObject:viewController.dataObject]; 
}
 .
 . 
@end 

 

Viewcontrolleratindex:The method first checks whether the valid page number is <0 (the user cannot return to the first page) or the number of pages to be retrieved exceeds the actual number of pagecontent arrays. If the index parameter is valid, create a new contentviewcontroller instance and set the dataobject attribute to the corresponding pagecontent entry (HTML string ).

The indexofviewcontroller method specifies a viewcontroller as the parameter and returns the index of this viewcontroller. It uses the dataobject attribute of viewcontroller to retrieve its index in the pagecontent array element.

Now let's look at two data source methods. They use these two convenient methods to return the View Controller of the current view controller "before" and "after:

 
- (UIViewController *)pageViewController: (UIPageViewController *)pageViewController viewControllerBeforeViewController: (UIViewController *)viewController {
     NSUInteger index = [self indexOfViewController:
        (contentViewController *)viewController];
     if ((index == 0) || (index == NSNotFound)) {
         return nil;
     }
      index--;
     return [self viewControllerAtIndex:index]; 
- (UIViewController *)pageViewController: (UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {
     NSUInteger index = [self indexOfViewController:
         (contentViewController *)viewController];
     if (index == NSNotFound) {
         return nil;
     }
      index++;
     if (index == [self.pageContent count]) {
         return nil;
     }
     return [self viewControllerAtIndex:index]; 
}
 

The next step is to create and instantiate the uipageviewcontroller class.

Instantiate uipageviewcontroller

Next, create and initialize the uipageviewcontroller instance. This process only needs to be performed once. Therefore, you can write the code in the viewdidload method of pageappviewcontroller. OpenPageappviewcontroller. mFile Modification viewdidload:

 

- (void)viewDidLoad {
     [super viewDidLoad];
     [self createContentPages];
     NSDictionary *options =
       [NSDictionary dictionaryWithObject:
      [NSNumber
 numberWithInteger:UIPageViewControllerSpineLocationMin]
      forKey: UIPageViewControllerOptionSpineLocationKey];
      self.pageController = [[UIPageViewController alloc]         initWithTransitionStyle:UIPageViewControllerTransitionStylePageCurl   navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal
        options: options];
      pageController.dataSource = self;
     [[pageController view] setFrame:[[self view] bounds]];
      contentViewController *initialViewController =
         [self viewControllerAtIndex:0];
     NSArray *viewControllers =
          [NSArray arrayWithObject:initialViewController];     
     [pageController setViewControllers:viewControllers
         direction:UIPageViewControllerNavigationDirectionForward
        animated:NO
        completion:nil];
      [self addChildViewController:pageController];
     [[self view] addSubview:[pageController view]];
     [pageController didMoveToParentViewController:self]; 
} 

 

All code ends here. Before compiling and running a program, analyze the code in the viewdidload method.

After building the data model, we created an nsdictionary object. This nsdictionary contains an options for page controrler object initialization options. Here, this option specifies that spine is located on the left side of the screen (spine is the spine of the book, where the book is bound, and the book is read from the other side ):

 

NSDictionary *options =     [NSDictionary dictionaryWithObject:     [NSNumber numberWithInteger:UIPageViewControllerSpineLocationMin]     forKey: UIPageViewControllerOptionSpineLocationKey]; 
 

In the next sentence, use the preceding options to instantiate uipageviewcontroller:

 
self.pageController = [[UIPageViewController alloc]    initWithTransitionStyle:UIPageViewControllerTransitionStylePageCurl   navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal   options: options]; 
 
Some configuration is required to make the class the data source of page controller. For example, to make the page full screen, we need to set its frame:
 
pageController.dataSource = self; 
[[pageController view] setFrame:[[self view] bounds]]; 
 
 

Before you can display the information on the 1st page, you must create a View Controller. This can call viewcontrolleratindex: convenient method. After obtaining a contentview controller, put it in an array object:

 
contentViewController *initialViewController =
     [self viewControllerAtIndex:0]; 
NSArray *viewControllers =
      [NSArray arrayWithObject:initialViewController]; 

 

Note that only one content View Controller is required. Because page controller is set to display only one page (single-sided) at a time ). If you configure pagecontroller to 2 pages (spine in the center) or double-sided, you need to create two content view controllers and put them in an array.

Then, assign the array object to View Controller and set the navigation direction to forward mode:

 
[pageController setViewControllers:viewControllers
      direction:UIPageViewControllerNavigationDirectionForward
     animated:NO
     completion:nil]; 
 

Finally, add the page vview controller to the current view:

 
[self addChildViewController:pageController];
 [[self view] addSubview:[pageController view]];
 [pageController didMoveToParentViewController:self]; 

 

Run the uipageviewcontroller Application

Click Run to run the program. The page 1st is displayed. Slide the screen from right to left. The screen will go to the next page. If you do the opposite, the screen will go to the previous page.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.