-
StackOverflow 文档
-
iOS 教程
-
UIPageViewController
-
以编程方式创建水平分页 UIPageViewController
- 由 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];
- 创建 UIPageViewController 实例。
UIPageViewController *pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll
navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal
options:nil];
- 数据源是必须实现
UIPageViewControllerDataSource
协议的当前类。
pageViewController.dataSource = self;
setViewControllers
将只添加第一个视图控制器,接下来将使用数据源方法添加到堆栈中
if (viewControllers.count) {
[pageViewController setViewControllers:@[[viewControllers objectAtIndex:0]]
direction:UIPageViewControllerNavigationDirectionForward
animated:NO
completion:nil];
}
- 添加 UIPageViewController 作为子视图控制器,以便从它的父视图控制器
appearance
和 rotation
事件接收。
[self addChildViewController:pageViewController];
pageViewController.view.frame = self.view.frame;
[self.view addSubview:pageViewController.view];
[pageViewController didMoveToParentViewController:self];
- 实现 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;
}
- 使用索引返回视图控制器的实用程序方法,如果索引超出范围,则返回 nil。
- (UIViewController *)childViewControllerAtIndex:(NSInteger)index
{
if (index <= ([viewControllers count] - 1)) {
return [viewControllers objectAtIndex:index];
} else {
return nil;
}
}