0A simple way to create horizontal page view controllers infinite pages
suggest change- Let’s create a new project, I’m choosing Single View Application for better demonstration
- Drag a page view controller to the storyboard, there are 2 things you should change after that:
1. Set the page view controller as initial view controller
2. Change the transition style to scroll
- And you need to create a UIPageViewController class, then set it as custom class of the page view controller on the storyboard
- Paste this code into your UIPageViewController class, you should get a colorful infinite paged app :)
class PageViewController: UIPageViewController, UIPageViewControllerDataSource {
override func viewDidLoad() {
self.dataSource = self
let controller = createViewController()
self.setViewControllers([controller], direction: .forward, animated: false, completion: nil)
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
let controller = createViewController()
return controller
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
let controller = createViewController()
return controller
}
func createViewController() -> UIViewController {
var randomColor: UIColor {
return UIColor(hue: CGFloat(arc4random_uniform(360))/360, saturation: 0.5, brightness: 0.8, alpha: 1)
}
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "View Controller")
controller.view.backgroundColor = randomColor
return controller
}
}
This is what the final project looks like, you get a view controller with different color with every scroll:
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents