31
32

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.

swiftで遷移元のviewcontrollerのインスタンスを取得する方法

Last updated at Posted at 2016-03-26

1画面戻るとき

viewContollerAからviewControllerBに画面遷移をしたときにviewControllerBでviewControllerAをインスタンスを取得したいとする。

let count = (self.navigationController?.viewControllers.count)! - 2
let vcA = self.navigationController?.viewControllers[count]

で取得ができる。
肝は-2とすること。

前のviewControllerによって処理を分けることも可能

let count = (self.navigationController?.viewControllers.count)! - 2
if count < 0 {
    // 戻るviewControllerがないとき(navigationController上で一番最初の画面のとき)
}
if let previousViewController = self.navigationController?.viewControllers[count] as? viewControllerA {
    // viewControlllerAの処理
} else {
    // それ以外のviewControllerの処理
}

複数戻るとき

例えば
vcA -> vcB -> vcC
でvcCで2画面前のvcAを取得したいとき

let count = (self.navigationController?.viewControllers.count)! - 3
let vcA = self.navigationController?.viewControllers[count]

といった具合でインスタンス化して取得することができる。

つまり、n画面前のviewControllerを取得したいときはn+1引けばよいということ

31
32
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
31
32

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?