LoginSignup
5
4

More than 3 years have passed since last update.

UINavigationControllerをSceneDelegateでRootViewにセットする時の注意点!

Last updated at Posted at 2020-12-12

この記事で言いたいこと

すごく初歩的ですが、
Storyboardを使っているのか、使っていないのかちゃんと意識しましょう!
著者はこれで2時間無駄にしました!
下記の🙅‍♂️これはダメです!を実施すると、当然のことながら、IBOutletがnilになります。
よって、ViewDidLoad(){ }でUIに値を入れようとしてもクラッシュします!

環境

  • Xcode : Version 12.2
  • Swift5

Storyboardを使う場合

//Storyboardを使用している場合は、StoryboardからViewControllerを生成しましょう。
      //🙆‍♂️これはOK! 
        let storyboard = UIStoryboard(name: "Main", bundle: .main)
        let vc = storyboard.instantiateInitialViewController() as! ViewController

      //🙅‍♂️これはダメです!  let vc = ViewController()

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

        guard let windowScene = (scene as? UIWindowScene) else { return }
        let window = UIWindow(windowScene: windowScene)
        let storyboard = UIStoryboard(name: "Main", bundle: .main)
        let vc = storyboard.instantiateInitialViewController() as! ViewController
        let navigation = UINavigationController(rootViewController: vc)
        window.rootViewController = navigation
        self.window = window
        window.makeKeyAndVisible()

    }
}

Storyboardを使わない場合

1.Main.storyboardを削除。
2.プロジェクトのTARGETS > InfoにあるMain storyboard file base nameという項目を削除。
Screen Shot 2020-12-12 at 1.32.31 PM.png


class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

        guard let windowScene = (scene as? UIWindowScene) else { return }
        let window = UIWindow(windowScene: windowScene)
        let vc = ViewController()
        let navigation = UINavigationController(rootViewController: vc)
        window.rootViewController = navigation
        self.window = window
        window.makeKeyAndVisible()

    }
}

参照

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