LoginSignup
71
65

More than 5 years have passed since last update.

【Swift】UIWindowのrootViewControllerに代入したUINavigationControllerを別のUINavigationControllerに切り替える方法

Last updated at Posted at 2014-11-09

UINavigationControllerによる画面遷移をアプリ起動時の最初の画面から行いたい時があります。
そんな時はAppDelegateのapplication application:didFinishLaunchingWithOptionsメソッド内でwindow?.rootViewControllerにUINavigationControllerのインスタンスを代入するわけですが、window?.rootViewControllerに後で他のUINavigationControllerのインスタンスを代入する方法で少し詰まったのでメモしておきます。

//新たにrootViewControllerにする画面を生成
var newRootVC = UIViewController()
var navigationController = UINavigationController(rootViewController: newRootVC)

UIApplication.sharedApplication().keyWindow?.rootViewController = navigationController

上記のソースコードを画面遷移として書いてやればオーケー。
それまで画面遷移で連なっていたUINavigationControllerとその遷移している全ての画面は破棄されます。

解説するとUIApplication.sharedApplication().keyWindow?で現在最前面のUIWindowを取得できるので、それのrootViewControllerに新たなrootViewとなる遷移先UIViewControllerをrootViewControllerをもつUINavigationControllerを代入しています。

71
65
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
71
65