LoginSignup
27

More than 3 years have passed since last update.

Swift5 UIPageViewControllerの使い方

Last updated at Posted at 2019-05-10

こちらの記事が古かったのでコピペで動くものを共有します。

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で指定しないと(多分)

    override init(transitionStyle style: UIPageViewController.TransitionStyle, navigationOrientation: UIPageViewController.NavigationOrientation, options: [UIPageViewController.OptionsKey : Any]? = nil) {
        super.init(
            transitionStyle: .scroll,
            navigationOrientation: .horizontal,
            options: options
        )
    }

サクッと動かしたかったけど、Storyboard使ったパクリ記事ばっかで😹

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
27