返回值的文档 presentationIndexForPageViewController: 说:
返回要在页面指示符中反映的所选项的索引。
但是,这很模糊。当用户滚动浏览页面视图控制器时,它是否会调用此方法并期望正确的索引?
此外,无法保证何时
pageViewController:viewControllerBeforeViewController: 和 pageViewController:viewControllerAfterViewController:。文档刚提到:
响应于导航手势,[An]对象[提供]视图控制器根据需要基于页面视图控制器。
事实上,我已经看到在某些情况下发生缓存。例如,如果您向前导航两个页面,它看起来只会取消分配视图控制器。否则,它希望将其保留在缓存中,以防用户在页面视图控制器中向后移动。
这是否意味着我需要一致的方式来通过注册来了解当前正在显示哪个页面 UIPageViewControllerDelegate
接着 不断更新这个值?
关于
presentationCountForPageViewController: 和
presentationIndexForPageViewController:,文件说明:
这两种方法都在之后调用 setViewControllers:方向:动画:完成: 方法被调用。在手势驱动导航之后,不会调用这些方法。索引会自动更新,预计视图控制器的数量将保持不变。
因此,看起来我们只需要在之后立即返回有效值 setViewControllers:方向:动画:完成: 叫做。
每当我实现数据源时,我都会创建一个辅助方法, 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];
}