LoginSignup
6
5

More than 5 years have passed since last update.

30行の単一ファイルでUIPageView

Last updated at Posted at 2016-10-21

【決定版】UIPageViewControllerの使い方(Swift) - Qiita

で勉強して、作ってみました。

Main_storyboard.png

PageViewController.swiftを作って、

PageViewController_swift.png

UIPageViewControllerのカスタムビューにセット。

Main_storyboard3.png

そのまま2カ所編集します。

cc37c4c2-626f-0693-c34b-397066a836ed.png

次の「Use Storyboad ID」を忘れずに。「second」「third」も同様。

Main_storyboard2.png

PageViewController.swift
import UIKit

class PageViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {

    let pageList = ["first", "second", "third"]

    override func viewDidLoad() {
        super.viewDidLoad()
        dataSource = self  // 忘れがち
        setViewControllers([storyboardId("first") as! UIViewController], direction: .Forward, animated: true, completion: nil)
    }

    // 便利
    func storyboardId(strID: String) -> AnyObject! {
        return (storyboard?.instantiateViewControllerWithIdentifier(strID))
    }

    // 1ページ進む
    func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
        let index = pageList.indexOf(viewController.restorationIdentifier!)
        if index < (pageList.count - 1) {
            return (storyboardId(pageList[index! + 1]) as! UIViewController)
        } else {
            return nil
        }
    }

    // 1ページ戻る
    func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
        let index = pageList.indexOf(viewController.restorationIdentifier!)
        if 0 < index {
            return (storyboardId(pageList[index! - 1]) as! UIViewController)
        } else {
            return nil
        }
    }

    // Page Controlを表示する(以下のコードを書いただけで自動で表示されます)
    func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
        return pageList.count
    }    
    func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int {
        return 0
    }
}

しばしば文句を言いたくなるXcodeですが、いいところもありますね😅

追記:【Swift】UIPageViewControllerの使い方。PageControlの色を変更する。 | はじはじアプリ体験記を見たら良いコードだったので真似させていただきました。

6
5
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
6
5