LoginSignup
0
1

More than 5 years have passed since last update.

PageViewControllerで次(前)のViewControllerを返すところでハマった

Last updated at Posted at 2017-11-07

概要

日記帳のようなアプリを作る際にPageViewControllerを使って実装したが、
Outlet接続したUILabelが全てnilになってしまってハマったのでメモ。

PageViewControllerで必要なDelegateメソッド

func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
      // 前のページを作る(ViewController)
      // そのViewControllerにページ番号をセット
    }
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
      //次のページを作って返す
      //そのViewControllerにページ番号をセット
    }

上記のメソッドで生成されるViewController(下の図の一番右)

class DiaryContentViewController: UIViewController {

    var pageIndex :Int? {
      didSet{
         pageIndexLabel.text = "\(pageIndex)"
      }
    }

    @IBOutlet weak var pageIndexLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

スクリーンショット 2017-11-08 0.37.29.png

やりたかったこと

  • ページをめくった際に、ページ番号を更新
  • 更新されたページ番号をコンテンツとなるViewControllerにセット
  • セットされたタイミングでUILabelにセット

ここで問題が...
次(前)のページを返すメソッドでnilで落ちる...

原因

present/pushで画面遷移が行われてない状態だとアウトレット接続がまだ行われてないのでnilになる

解決策

override func viewDidLoad() {
        super.viewDidLoad()
        self.pageIndexLabel.text = "\(pageIndex!)"
    }

コンテンツのとなるViewControllerのviewDidLoadで処理を行う

0
1
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
0
1