使用具有多个视图的UIPageViewController

时间:2013-07-24 15:25:10

标签: ios objective-c uipageviewcontroller

我有以下代码来创建UIPageViewController:

- (void)viewDidLoad
{
[super viewDidLoad];

self.index = 0;

self.pageContainer = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];

self.pageContainer.dataSource = self;
[[self.pageContainer view] setFrame:[[self view] bounds]];

DMSignUp1ViewController *first = [[DMSignUp1ViewController alloc] init];
DMSignUp2ViewController *second = [[DMSignUp2ViewController alloc] init];

self.viewControllers = [[NSArray alloc] initWithObjects:first, second, nil];

[self.pageContainer setViewControllers:self.viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];

[self addChildViewController:self.pageContainer];
[[self view] addSubview:[self.pageContainer view]];
[self.pageContainer didMoveToParentViewController:self];
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController
{
    if(self.index == 0) {
        return nil;
    }

    self.index--;
    return [self.viewControllers objectAtIndex:self.index];
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController
{
    if(self.index == 1) {
        return nil;
    }

    self.index++;
    return [self.viewControllers objectAtIndex:self.index];
}

我有两个UIViewControllers:我创建的DMSignUp1和2,然后放在viewControllers数组中。

当我去运行它时,我收到以下错误:'提供的视图控制器的数量(2)与请求的转换所需的数量(1)不匹配'

我理解的是因为我传递的数组用作视图控制器。那么如何设置我想使用数组中的第一个视图控制器?

2 个答案:

答案 0 :(得分:4)

在ViewController.m文件的末尾添加以下方法

- (DMSignUp1ViewController *)viewControllerAtIndex:(NSUInteger)index {

    DMSignUp1ViewController *first= [[DMSignUp1ViewController alloc] initWithNibName:@"APPChildViewController" bundle:nil];
    first.index = index;

    return childViewController;
}

并且,替换以下代码

DMSignUp1ViewController *first = [[DMSignUp1ViewController alloc] init];
DMSignUp2ViewController *second = [[DMSignUp2ViewController alloc] init];

self.viewControllers = [[NSArray alloc] initWithObjects:first, second, nil];

使用

APPChildViewController *initialViewController = [self viewControllerAtIndex:0];

    NSArray *viewControllers = [NSArray arrayWithObject:initialViewController];

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

希望这可以帮助你...

答案 1 :(得分:2)

如果在使用UIPageViewController spineLocation时将UIPageViewControllerSpineLocationMid设置为[self.pageContainer setViewControllers:以外的任何其他设置,则只能传递具有一个视图控制器的数组。这个API说Controllers并不是很清楚。然后,当viewControllers通过UIPageViewController请求时,您可以提供额外的dataSource

Link to the spine reference