こちらの記事が古かったのでコピペで動くものを共有します。
.swift
final class ViewController: UIPageViewController {
private var controllers: [UIViewController] = []
override func viewDidLoad() {
super.viewDidLoad()
let colors: [UIColor] = [.red, .orange, .green, .cyan]
controllers = colors.map { color in
let c = UIViewController()
c.view.backgroundColor = color
return c
}
setViewControllers([controllers[0]],
direction: .forward,
animated: false,
completion: nil)
dataSource = self
}
}
extension ViewController: UIPageViewControllerDataSource {
/// 右にスワイプ(戻る)した場合のメソッド
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
if let index = controllers.firstIndex(of: viewController),
index > 0 {
return controllers[index-1]
} else {
return nil
}
}
/// 左にスワイプ(進む)した場合のメソッド
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
if let index = controllers.firstIndex(of: viewController),
index < controllers.count-1 {
return controllers[index+1]
} else {
return nil
}
}
func presentationCount(for pageViewController: UIPageViewController) -> Int {
return controllers.count
}
}
transitionStyleがgetterなので変更したい場合はinitで指定しないと(多分)
.swift
override init(transitionStyle style: UIPageViewController.TransitionStyle, navigationOrientation: UIPageViewController.NavigationOrientation, options: [UIPageViewController.OptionsKey : Any]? = nil) {
super.init(
transitionStyle: .scroll,
navigationOrientation: .horizontal,
options: options
)
}
サクッと動かしたかったけど、Storyboard使ったパクリ記事ばっかで😹