我应该在presentationIndexForPageViewController中返回什么:对于我的UIPageViewControllerDataSource?

时间:2015-04-20 20:35:53

标签: ios objective-c uipageviewcontroller

presentationIndexForPageViewController:返回值的文档说:

  

返回要在页面指示符中反映的所选项目的索引。

但是,这很模糊。当用户滚动浏览页面视图控制器时,它是否会调用此方法并期望正确的索引?

此外,无法保证何时 pageViewController:viewControllerBeforeViewController:pageViewController:viewControllerAfterViewController:。文档提到:

  

[An]对象[提供]根据需要为页面视图控制器提供视图控制器,以响应导航手势。

事实上,我已经看到在某些情况下发生缓存。例如,如果您向前导航两个页面,它看起来只会被取消分配。否则,如果用户在页面视图控制器中向后移动,它希望将其保留在缓存中。

这是否意味着我需要通过注册为UIPageViewControllerDelegate然后constantly updating this value来确定当前显示哪个页面的一致方式?

1 个答案:

答案 0 :(得分:9)

关于 presentationCountForPageViewController:presentationIndexForPageViewController:,文档说明:

  

调用setViewControllers:direction:animated:completion:方法后调用这两个方法。在手势驱动导航之后,不会调用这些方法。索引会自动更新,预计视图控制器的数量将保持不变。

因此,看起来我们只需要在调用setViewControllers:direction:animated:completion:后立即返回有效值。

每当我实现数据源时,我都会创建一个帮助方法showViewControllerAtIndex:animated:,并跟踪要在属性presentationPageIndex中返回的值:

@property (nonatomic, assign) NSInteger presentationPageIndex;
@property (nonatomic, strong) NSArray *viewControllers; // customize this as needed

// ...

- (void)showViewControllerAtIndex:(NSUInteger)index animated:(BOOL)animated {
    self.presentationPageIndex = index;
    [self.pageViewController setViewControllers:@[self.viewControllers[index]] direction:UIPageViewControllerNavigationDirectionForward animated:animated completion:nil];
}

#pragma mark - UIPageViewControllerDataSource

- (NSInteger)presentationIndexForPageViewController:(UIPageViewController *)pageViewController {
    return self.presentationPageIndex;
}

然后,您可以使用此方法显示正确的视图控制器,并使所选索引显示正确的值:

- (void)viewDidLoad {
    [super viewDidLoad];
    [self showViewControllerAtIndex:0 animated:NO];
}

- (IBAction)buttonTapped {
    [self showViewControllerAtIndex:3 animated:YES];
}
相关问题