Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
502 views
in Technique[技术] by (71.8m points)

ios - how to make UIPageViewController reuse controller like tableview reuse cell?

I need a way to make UIPageViewController reuse controllers to save memory, because I have a huge number of pages to show! I did the basic implementation of the UIPageViewController but couldn't manage to make controller reusable, please advice!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To solve this problem in my current project, I cache all view controllers that are created as pages for the UIPageViewController in a Set. Whenever the UIPageViewController requests a new view controller from its data source, I filter out an unused from that cache by checking the parentViewController property; if no unused view controller is available, a new one is created.

My setup of the UIPageViewController and the cache looks similar to this:

class MyPageViewController: UIPageViewController {
    private var reusableViewControllers = Set<MyViewController>()
    init() {
      super.init(/* ... */)
      self.dataSource = self

      let initialViewController = self.unusedViewController()

      // Configure the initial view controller
      // ...

      self.setViewControllers([ initialViewController ], 
                              direction: .Forward, 
                              animated: false, 
                              completion: nil)
    }

  // This function returns an unused view controller from the cache
  // or creates and returns a new one
  private func unusedViewController() -> MyViewController {
    let unusedViewControllers = reusableViewControllers.filter { $0.parentViewController == nil }
    if let someUnusedViewController = unusedViewControllers.last {
        return someUnusedViewController
    } else {
        let newViewController = MyViewController()
        reusableViewControllers.insert(newViewController)
        return newViewController
    } 
  }
}

The data source uses the same function to obtain an unused view controller:

extension MyPageViewController: UIPageViewControllerDataSource {
  func pageViewController(pageViewController: UIPageViewController,
                          viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
        let nextViewController = unusedViewController()

        // Configure the next view controller for display
        // ...

        return nextViewController
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...