0

We need to build a horizontal swipe-able page, with number of page range from 2 to infinity. User has the ability to add and remove any page.

We really do not want to create all and keep all UIViewController in memory. That is highly inefficient.

We hope, UIPageViewController can have mechanism, similar to UICollectionView cell reusing mechanism.

Since I'm pretty familiar how Android handling this case. Let me describe it below

  1. When you want to have 100 swipe-able pages, Android will only create 2 (This figure is configurable) view hierarchy. If the view is not visible, the view hierarchy will be destroyed, and a new view heirarhy for the newly visible page will be created. All the view hierarchy recreation, is done through Fragment's onCreateView (Android Fragment is similar to iOS ViewController)
  2. When you swipe from page 1 direcly to page 4, then swipe back again to page 1, the view for page 1 will be re-created via Fragment's onCreateView. However, how does Android restore multiple UI states in the page? If there is a RecyclerView (Similar to iOS UICollectionView) in page 1 being re-created, RecyclerView's previous scroll position will be restored via onRestoreInstanceState.

In Android, the mechanism 1 & 2, is pretty much offered by the Android framework out of the box. Not much work required at developer side.

I was wondering, how does iOS able to achieve the same thing?

I have seen a technique, described in https://stackoverflow.com/a/36876103/72437

However, it isn' clear, on how the UI state restoration state work? For instance, if I have an UICollectionView in page 1. How can I restore the UI state (scroll position) of UICollectionView, when I swipe back to page 1?

Cheok Yan Cheng
  • 47,586
  • 132
  • 466
  • 875

1 Answers1

0

Use a UICollectionView.

If you need to have controllers for each cell, load the controllers in the re-useable cell on cell initialization.

UICollectionViewCells are UIViews with reuse functionality built on top; they are only de-initialized when the UICollectionView is de-initialized. When your cell is created for the first time, also create the view controller inside (which holds the actual view you want to reuse). Use the cell reuse and configuration calls (e.g. cellForRowAt(indexPath) and prepareForReuse()) to setup your vc/view inside the cell. Dependency injection is great in this flow. Prefetch if you need to load a lot of data or have slow response times.

iOS will also optimize the number of cells being reused at a time (really should never be more than say 20, there can only be so many on the screen), so you wont have to worry about maintaining a set or tracking how many instances you have.

Use a page view indicator if you need that, or make your own.

If you want to develop your own reuse system, study that of UICollectionView(Cell) first because they do this very well imo.