코드 실행 시, "실행 시 검은 화면만 나오는 경우"  혹은 "Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value"의 오류가 발생하는 경우 (로드 과정에서 컴포넌트 속성을 수정하는 경우 ex) label.text = "...")

 

이번 경우에는 화면 이동을 위해 SceneDelegate.swift 내에서, 아래와 같이 코드를 추가해서 문제가 발생함

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 rootVC = HomeViewController()   // 오류 발생 원인 코드
    let navigationController = UINavigationController(rootViewController: rootVC)

    window.rootViewController = navigationController
    self.window = window
    window.makeKeyAndVisible()
}

 

StoryBoard 기반의 UIKit를 사용하기 때문에, 단순히 저렇게 생성자를 호출하는 방식으로는 VC가 정상적으로 생성되지 않음

아래와 같이 identifier를 기반으로 instantiateViewController 메소드를 호출하여 초기화해야함

// 해결 코드
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let rootVC = storyboard.instantiateViewController(identifier: "HomeViewController") as! HomeViewController

 

 

+ Recent posts