25
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swift5 UIPageViewControllerの使い方

Last updated at Posted at 2019-05-10

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

.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使ったパクリ記事ばっかで😹

25
27
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
25
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?