【问题标题】:What should I return in presentationIndexForPageViewController: for my UIPageViewControllerDataSource?我应该在 PresentationIndexForPageViewController: 中为我的 UIPageViewControllerDataSource 返回什么?
【发布时间】:2015-04-20 20:35:53
【问题描述】:
【问题讨论】:
标签:
ios
objective-c
uipageviewcontroller
【解决方案1】:
关于
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];
}