UIPageScrollView

Background

Working on my News App, I came to place where once again I need to do paging in a UIScrollView.

Local News

Local News

Paging is not difficult, but you need to take in account memory and caching. iOS does not do much for you, in solving this problem, however, Apple has documentation on how to achieve this including WWDC videos. 

The general idea is similar to how UITableViews & UICollectionView's work. Recycle views and only keep a minimal number of views in memory. 

UIPageScrollView

So I created a new class to do just that. UIPageScrollView.

UIPageScrollView abstracts all of that code. All you need to do is give 

  1. A parent UIViewController
  2. Code to create the page
  3. The number of pages
   1:  public override void ViewDidLoad()
   2:  {
   3:      base.ViewDidLoad();
   4:    
   5:      const int NumberOfImages = 14;
   6:   
   7:      ScrollPageView = new UIPageingScrollView(this, scrollPage =>
   8:      {
   9:          var imageFileName = string.Format("IMG_{0}.jpg", 1185 + scrollPage.Index);
  10:          var image = UIImage.FromFile(imageFileName);
  11:   
  12:          ViewControllerWithImage viewController;
  13:   
  14:          if (scrollPage.ViewController == null)
  15:          {
  16:              viewController = (ViewControllerWithImage)Storyboard.InstantiateViewController("imageVC");
  17:              scrollPage.ViewController = viewController;
  18:          }
  19:          else
  20:          {
  21:              viewController = (ViewControllerWithImage)scrollPage.ViewController;
  22:          }
  23:   
  24:          viewController.Image = image;
  25:      });
  26:   
  27:      ScrollPageView.NumberOfPages = NumberOfImages;
  28:     
  29:  }

Calling Code Overview

When the ViewController is null we need to create one. Otherwise, it is a recycled ViewController that is being used again. 

We then need to populate the ViewController/View based on our application logic.

 

Possible Additions

Currently, there isn't a UIPageControl. Possibly I'll add one in the future. 

 

The Code

An example project with the code can be found on Github at

https://github.com/kraigspear/UIPageScrollView

Download ZIP                 

For more detail watch the code demo below....

Video Demo