Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIPageViewController and setViewControllers:

I am having trouble understanding this line of code when I setup my UIPageViewController:

  [self.pageViewController setViewControllers:@[startingViewController]
                                      direction:UIPageViewControllerNavigationDirectionForward
                                       animated:NO
                                     completion:^(BOOL finished) {
                                         // Completion code
                                     }];

In most of the examples I have seen just a single UIViewController is passed into the setViewControllers and then the next one initiated using (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController. Why do we not init all the view controllers first and then pass them all into setViewControllers ?

Any pointers on this would be great, thanks

like image 855
KexAri Avatar asked Mar 26 '26 19:03

KexAri


2 Answers

Why do we not init all the view controllers first and then pass them all into setViewControllers ?

Because that isn't how a UIPageViewController works. It has, at every moment, either one page at a time or two pages at a time (shown simultaneously, like a physical book lying open). Most people use it to show one page at a time, so when you call setViewControllers:, you supply that one page.

If you wanted to "init all the view controllers first", you wouldn't be using a UIPageViewController in the first place - you'd be using an ordinary UIScrollView. But that would be extremely heavyweight. Suppose (as is in fact the case in one of my apps) there were two thousand pages. Two thousand view controllers all at once??? You'd run out of memory at startup! The whole point of a UIPageViewController is that it is lightweight because, generally speaking, only one child view controller exists at a time. It is dynamic, not static.

like image 123
matt Avatar answered Mar 29 '26 09:03

matt


The setViewControllers method can be thought of as setting the current page. The documentation tells you to pass in a certain number of viewControllers to this method depending on how many pages are shown at a time with the given settings.

enter image description here

From there you can implement viewControllerAfterViewController and viewControllerBeforeViewController to provide any other pages you want to display when the user swipes.

As to why they implemented it like this, I'd say so you can choose the next page dynamically and because the lazy loading could have huge space benefits.

like image 24
JordanC Avatar answered Mar 29 '26 08:03

JordanC