iOS A simple way to create horizontal page view controllers ( infinite pages )


Example

  1. Let's create a new project, I'm choosing Single View Application for better demonstration

enter image description here

  1. 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

enter image description here

  1. And you need to create a UIPageViewController class, then set it as custom class of the page view controller on the storyboard

  2. 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:

enter image description here