LoginSignup
4
3

More than 5 years have passed since last update.

あるViewControllerからどのViewControllerへ遷移したかを知る方法

Last updated at Posted at 2017-09-05

UIViewController#didMoveで監視すると良い感じ。

  • 自身がNavigationController
  • pushして遷移
  • presentして遷移(これもNavigationControllerで、中身のViewControllerで特定したい)

といったケースが多いと思うので、その辺を考慮したコードになってます。

override func didMove(toParentViewController parent: UIViewController?) {
    var targetController: UIViewController?
    if self.presentedViewController is UINavigationController {
        // presentした先がNavigationControllerだった場合
        // 一番最初のViewControllerを遷移先と判断
        targetController = self.presentedViewController!.childViewControllers.first
    } else if self.presentedViewController != nil {
        targetController = self.presentedViewController
    } else {
        // pushしたViewControllerを得る
        // 自身だったらpushで遷移してないので無視
        if self != self.navigationController?.viewControllers.last {
          targetController = self.navigationController?.viewControllers.last
        }
    }
}

一点問題がある。どうもpushした時、didMoveが2回呼ばれるようである。1回しか処理したくない場合、これではだめかもしれない。

4
3
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
4
3