如何使UIPageViewController重用控制器,如tableview重用单元格?
我需要一种使UIPageViewController重用控制器以节省内存的方法,因为我要显示大量的页面! 我做了UIPageViewController的基本实现,但是无法使控制器可重用,请咨询!
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!
为解决当前项目中的此问题,我将所有作为UIPageViewController
页面创建的视图控制器缓存在Set
中.每当UIPageViewController
从其数据源请求新的视图控制器时,我都会通过检查parentViewController
属性从该缓存中过滤掉未使用的视图控制器;如果没有可用的未使用的视图控制器,则会创建一个新的视图控制器.
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.
我对UIPageViewController
和缓存的设置类似于以下内容:
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
}
}