iOS 以编程方式创建水平分页UIPageViewController

示例

  1. 由UIPageViewController管理的视图控制器的初始化数组。添加具有属性的基本视图控制器类,该类identifier将在使用UIPageViewController数据源方法时用于标识视图控制器。让视图控制器从该基类继承。

UIViewController *firstVC = [[UIViewController alloc] init]; 
firstVC.identifier = 0  
UIViewController *secondVC = [[UIViewController alloc] init];   
secondVC.identifier = 1
NSArray *viewControllers = [[NSArray alloc] initWithObjects: firstVC, secondVC, nil];

  1. 创建UIPageViewController实例。

UIPageViewController *pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll
                                                                           navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal
                                                                                         options:nil];

  1. 数据源是当前类,必须实现UIPageViewControllerDataSource协议。

pageViewController.dataSource = self;

  1. setViewControllers 将仅添加第一个视图控制器,然后使用数据源方法将下一个添加到堆栈

if (viewControllers.count) {
    [pageViewController setViewControllers:@[[viewControllers objectAtIndex:0]]
                                 direction:UIPageViewControllerNavigationDirectionForward
                                  animated:NO
                                completion:nil];
}

  1. 将UIPageViewController添加为子视图控制器,以便它将从其父视图控制器appearance和rotation事件接收。

 [self addChildViewController:pageViewController];
 pageViewController.view.frame = self.view.frame;
 [self.view addSubview:pageViewController.view];
 [pageViewController didMoveToParentViewController:self];

  1. 实现UIPageViewControllerDataSource方法

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController
      viewControllerBeforeViewController:(UIViewController *)viewController
{
    index = [(Your View Controler Base Class *)viewController identifier];
    index--;
    return [self childViewControllerAtIndex:index];
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController
       viewControllerAfterViewController:(UIViewController *)viewController
{
    index = [(Your View Controler Base Class *)viewController identifier];
    index++;
    return [self childViewControllerAtIndex:index];
}

- (NSInteger)presentationCountForPageViewController:(UIPageViewController *)pageViewController
{
    return [viewControllers count];
}

- (NSInteger)presentationIndexForPageViewController:(UIPageViewController *)pageViewController
{
    return index;
}

  1. 一种使用索引返回视图控制器的实用程序方法,如果索引超出范围,则返回nil。

- (UIViewController *)childViewControllerAtIndex:(NSInteger)index
{
    if (index <= ([viewControllers count] - 1)) {
        return [viewControllers objectAtIndex:index];
    } else {
        return nil;
    }
}