コードでrootViewControllerを指定する

Xcodeで新しくProjectを作ると、デフォルトでMain.storyboardがrootになるけれど、StoryBoardを使わずにrootViewControllerを設定したい事が多いのでメモ。

手順

1. Main.storyboardの指定を削除する

  • Single View App を選択してproject作成
  • Main.storyboard ファイルを消す
  • Target > General > Development Info > Main Interface のMainを消す

f:id:muchan611:20190714154239p:plain

2. AppDelegate.swift を編集

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool 関数の中身を以下のように書き換える。

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    let rootViewController = RootViewController() #ここはrootViewControllerにしたいViewControllerを指定する
    self.window = UIWindow(frame: UIScreen.main.bounds)
    self.window?.rootViewController = rootViewController
    self.window?.makeKeyAndVisible()
    return true
}

NavigationControllerをセットしたい場合は、以下のようにする

let navigationViewController = UINavigationController(rootViewController: rootViewController)
self.window?.rootViewController = navigationViewController

これで任意のViewControllerをrootViewControllerに指定してビルドできる。