使って創ってApp

ソフトウェアを使ったり作ったりするブログです

NavigationControllerで移動する一つ前のViewControllerを取得する iOSアプリ開発

iOSアプリ開発で NavigationController を使っている際、移動前の ViewController を取得したかったのでドキュメントを少し眺めてみました。

developer.apple.com

移動前の ViewController の取得方法は UINavigationController Class Reference に書いてありましたので備忘録として残しておきます。

開発環境

NavigationControllerで移動する一つ前のViewControllerを取得する

UINavigationController に属する ViewController 達は、画面を移動して表示される度に NavigationController が持つ配列に後入れで格納されます。それでは一つ前の ViewController を取得する方法を紹介します。

まず、自身(ViewController のサブクラス)を保有する NavigationController を呼び出します。その中には移動前の全ての ViewController が収められている ViewContllers 配列があります。その配列の後ろから二番目に、移動前の ViewController があります。

UINavigationViewController の ViewController のリファレンスには以下のように書いてありました。

The root view controller is at index 0 in the array, the back view controller is at index n-2, and the top controller is at index n-1, where n is the number of items in the array.

UINavigationController Class Reference より引用

簡単に書くと、コードは以下のようになります。

let navc = self.navigationController!
let viewc = navc.viewControllers[navc.viewControllers.count - 2]