以程式設計方式建立水平分頁 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 作為子檢視控制器,以便從它的父檢視控制器 appearancerotation 事件接收。
 [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;
    }
}