この記事で言いたいこと
すごく初歩的ですが、
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という項目を削除。
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()
}
}