Use UIPageViewController
. For example:
import UIKit
class MyPageViewController : UIPageViewController {
fileprivate var currentIndex = 0
// Setup
private func setup() {
// Delegation
self.delegate = self
self.dataSource = self
// Init
self.reloadPages(index: 0)
}
// MARK: - Lifecycle Methods
override func viewDidLoad() {
super.viewDidLoad()
self.setup()
}
// MARK: - Private Methods
fileprivate func reloadPages(index: Int) {
if let firstVc = self.cellForViewAt(index: index) {
self.setViewControllers([firstVc], direction: .forward, animated: true, completion: nil)
}
}
}
// MARK: - Cell
extension MyPageViewController {
fileprivate func cellForViewAt(index: Int) -> UIViewController? {
let vc = MyStoryboard().myCellViewController()
vc.pageIndex = index
return vc
}
}
// MARK: - Page methods
extension MyPageViewController : UIPageViewControllerDelegate, UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController, spineLocationFor orientation: UIInterfaceOrientation) -> UIPageViewControllerSpineLocation {
return .none
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
if let controller = viewController as? PageViewControllerProperties {
let newIndex = controller.pageIndex - 1
return self.cellForViewAt(index: newIndex)
}
return nil
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
if let controller = viewController as? PageViewControllerProperties {
let newIndex = controller.pageIndex + 1
return self.cellForViewAt(index: newIndex)
}
return nil
}
func pageViewControllerPreferredInterfaceOrientationForPresentation(_ pageViewController: UIPageViewController) -> UIInterfaceOrientation {
return .portrait
}
func pageViewControllerSupportedInterfaceOrientations(_ pageViewController: UIPageViewController) -> UIInterfaceOrientationMask {
return .portrait
}
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if completed {
// Complete action
}
}
func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {
// Expecting just 1
if let vc = pendingViewControllers.first as? PageViewControllerProperties {
self.currentIndex = vc.pageIndex
}
}
}
// MARK: - Um protocolo simples para registrar o pageIndex em todas as classes-células
protocol PageViewControllerProperties : class {
var pageIndex : Int { get set }
}