如果用户移动过快,UIPageViewController视图就会出现混乱



我有一个UIPageViewController,它使用一个整数来判断它在哪个页面上。它工作得很好,但如果用户快速滑动几次以到达更远的页面,整数的变化速度会比视图更快,然后整个事情就崩溃了(应用程序认为它在第7页,而它本可以显示第3页)。我做错了什么?有什么不同的方法可以告诉我在哪里吗?谢谢

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {
    if (pageNumber == 0) {
        pageNumber++;
        NSLog(@"%i", pageNumber);
        Two *two = [[Two alloc] init];
        return two;
    } else if (pageNumber == 1) {
        pageNumber++;
        NSLog(@"%i", pageNumber);
        Three *three = [[Three alloc] init];
        return three;
    } else if (pageNumber >= 2) {
        return nil;
    } else {
        return nil;
    }
}

问题是您认为pageNumber是理所当然的。UIPageViewController只能请求下一个viewController来预加载它,而您已经在增加pageNumber了。

当你注意到"如果用户抓住页面的边缘并开始移动它,但随后将其放回并停留在当前页面上,也会发生这种情况。"

此方法获取参数的UIViewController,这是您拥有的唯一实际引用

由于你只有三页,解决这个问题的一种方法是:

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController
{
    if ([viewController isKindOfClass: [One class]])
    {
        Two *two = [[Two alloc] init];
        return two;
    }
    else if ([viewController isKindOfClass: [Two class]])
    {
        Three *three = [[Three alloc] init];
        return three;
    }
    else
    {
        return nil;
    }
}

注意:这段代码不是最好的解决方案——我只是想指出,你不应该在viewControllerAfterViewController:/viewControllerBeforeViewController: 中简单地增加/减少pageNumber

在此之前,您还可以[[... alloc ]init] viewControllers,并将UIPageViewControllerDataSource方法中viewControllers的初始化活动减少到最多loadView(如果未加载)。例如(缩写):

    ...
    if ([viewController isKindOfClass: [One class]])
    {
        //Two *two = [[Two alloc] init]; //called before and two is someone's property
        if (![two isViewLoaded]) [two loadView];
        return two;
    }
    else if ...

对于更多页面,您也可以尝试标记viewControllers(在初始化期间)。由于UIViewController本身没有标记属性,您可以使用viewController.view.tag或子类UIViewController,并为其添加pageNumber属性(这可能接近于解决方案。

最新更新