I have a UIPageViewController that uses an integer to tell which page it is on. It works fine, but if the user quickly swipes several times to get to a page further back, the integer changes more quickly than the views do, and then the whole thing falls apart (the app thinks it is on page 7 when it could be displaying page 3). What am I doing wrong? Is there a different method I should use to tell where I am? Thanks.
- (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;
}
}
The problem is that you’re taking
pageNumberfor granted.UIPageViewControllercould only be asking for nextviewControllerto preload it and you’re already increasingpageNumber.You were close when you noticed that “this also happens if a user grabs the edge of the page and starts to move it, but then puts it and back stays on the current page.”
This method gets
UIViewControllerfor parameter and that is the only real reference you have.Since you only have three pages one way to solve this would be:
Note: this code is not the best solution – i’m just trying to point out that you shouldn’t be simply increasing/decreasing
pageNumberinviewControllerAfterViewController:/viewControllerBeforeViewController:You could also
[[... alloc ]init]viewControllers before all this and reduce initialization activity of viewControllers inUIPageViewControllerDataSourcemethods toloadView(if it’s not loaded) at most. For example (abbreviated):For more pages you could also try tagging viewControllers (during their initialization). Since
UIViewControlleritself doesn’t have a tag property you could probably useviewController.view.tagor sublcassUIViewControllerand add it apageNumberproperty (this would probably be close to THE solution.