Last active
July 24, 2023 06:08
-
-
Save enomoto/5d32d9b02f464f473fad18cbe94c28c7 to your computer and use it in GitHub Desktop.
UIPageViewController with inifinite scrolling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
final class ContainerViewController: UIViewController { | |
private let pageViewController: UIPageViewController = .init(transitionStyle: .scroll, navigationOrientation: .horizontal) | |
private let childViews: [UIViewController] = { | |
let vc0 = UIViewController() | |
vc0.view.backgroundColor = .red | |
let vc1 = UIViewController() | |
vc1.view.backgroundColor = .red.withAlphaComponent(0.6) | |
let vc2 = UIViewController() | |
vc2.view.backgroundColor = .red.withAlphaComponent(0.4) | |
let vc3 = UIViewController() | |
vc3.view.backgroundColor = .red.withAlphaComponent(0.2) | |
return [vc0, vc1, vc2, vc3] | |
}() | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
view.backgroundColor = .black | |
if let pageView = pageViewController.view { | |
view.addSubview(pageView) | |
pageView.translatesAutoresizingMaskIntoConstraints = false | |
NSLayoutConstraint.activate([ | |
pageView.leadingAnchor.constraint(equalTo: view.leadingAnchor), | |
pageView.trailingAnchor.constraint(equalTo: view.trailingAnchor), | |
pageView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), | |
pageView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor), | |
]) | |
pageView.backgroundColor = .white | |
} | |
pageViewController.dataSource = self | |
pageViewController.setViewControllers([childViews[0]], direction: .forward, animated: false) | |
} | |
} | |
extension ContainerViewController: UIPageViewControllerDataSource { | |
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { | |
guard let index = childViews.firstIndex(of: viewController) else { return nil } | |
if index > 0 { | |
return childViews[index - 1] | |
} else { | |
return childViews.last | |
} | |
} | |
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { | |
guard let index = childViews.firstIndex(of: viewController) else { return nil } | |
if index < childViews.count - 1 { | |
return childViews[index + 1] | |
} else { | |
return childViews.first | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment