我创建了一个UIPageViewController
,其中大部分将包含同一UIViewController
类的多个实例。为了节省用户滑动时的存储空间,我尝试实现此Reusable ViewControllers的版本,如下所示。
Reusabel页面
var pages:[TestViewController] = [TestViewController](){
didSet{
print("Pages count: \(pages.count)")
}
}
private func unusedViewController() -> TestViewController {
let unusedViewControllers = pages.filter { $0.parent == nil }
if let someUnusedViewController = unusedViewControllers.first {
return someUnusedViewController
} else {
let newViewController = TestViewController()
pages.append(newViewController)
return newViewController
}
}
在大多数情况下,这似乎行之有效,无论我创建多少页面,在pages
数组中始终只有3个ViewController。我在查找用户所在的当前页码的当前索引时遇到了一些困难。这使得难以限制有多少页以及确定用户向哪个方向滑动。下面是我对数据源的实现,尽管它并没有达到我希望的那样。谢谢您的帮助
UIPageViewControllerDataSource
var index = 0
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
if index == 0{
return nil
}
index -= 1
let vc = unusedViewController()
vc.view.backgroundColor = .gray
vc.index = index
vc.label.text = String(index)
return vc
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
if index >= 5{
return nil
}
index += 1
let vc = unusedViewController()
vc.view.backgroundColor = .blue
vc.index = index
vc.label.text = String(index)
return vc
}