LoginSignup
2
2

More than 3 years have passed since last update.

UIPageViewControllerをEnumで管理する

Posted at

実務でコードを書いてる時に、UIPageViewControllerをEnumでいい感じに書いているコードに出会ったので、
自分のための備忘録も兼ねて、ご紹介します

実行環境

Xcode: Version 11.6

実装

PageViewController親の実装

PageViewControllerの親になるクラスには、Enumを使って、載せたいコンテンツを定義します
今回は例として以下のようなEnumを定義します
(Enumのコレクションの扱いを楽にする為に、CaseIterableを継承させています)
また、UIPageViewControllerはすでに宣言されていることとします(今回のサンプルはコードで宣言しています)

BasePageViewController.swift
enum Content: CaseIterable {
    case first, second, third

    var title: String {
        switch self {
        case .first:
             return "1番目のViewController"
        case .second:
             return "2番目のViewController"
        case .third:
             return "3番目のViewController"
        }
     }

     // ここで載せたいViewControllerを定義する
     func instantiated() -> UIViewController() {
        switch self {
        case .first:
             return ContentViewController(type: self)
        case .second:
             return ContentViewController(type: self)
        case .third:
             return ContentViewController(type: self)
        }
     }
}

その後、このような感じでViewControllerのインスタンスを作成して、配列を作成します

BasePageViewController.swift
private lazy var viewControllers: [UIViewController] = {
    return Content.allCases.map{ $0.instantiated() }
}()

あとは、それを定義してあるUIPageViewControllerに渡してあげます

BasePageViewController.swift

// ~~~
override func viewDidLoad() {
    super.viewDidLoad()

    // ~~~ 省略
    // ~~~

    // viewDidLoadが走るタイミングで表示させるViewControllerを指定する
    pageViewController.setViewControllers([viewControllers[0]], direction: .forward, animated: true)
}
// ~~~

残りはUIPageViewControllerのDataSourceの実装が必要となりますが、
これだけでEnumで管理できるようになりました🤙

PageViewController子の実装

Enumで定義した子のViewControllerでは以下のようにContentを受け取っています

ContentViewController.swift
private let contentType: BasePageViewController.Content

init(type: BasePageViewController.Content) {
    self.contentType = type
    super.init(nibName: nil, bundle: nil)
}

// 以下受け取ったContentを使って実装

完成

実際に上のコードを使って作ってみたものがこちら

最後

Enumで管理する方法はすごく便利ですね!
CollectionViewとかもEnumで管理すれば、またいい感じに書けますよね💪

最後まで読んでいただいてありがとうございました👀
何か修正等がございましたら、なんなりとお申し付けください🙇🏻‍♂️

ソースコード

サンプルプロジェクトのソースコードはこちら
https://github.com/Take111/PageViewControllerSample

参考にさせてもらった記事

・CaseIterableとは何か(https://dev.classmethod.jp/articles/wwdc18-swift-4-2-case-iterable/)

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2