IOS

앱 시작 시 Navigation Controller로 시작하기 (Programmatically)

스토리보드를 이용해서 네비게이션 컨트롤러를 만들고 루트 뷰 컨트롤러를 지정해주고 Storyboard Entry Point를 네비게이션 컨트롤러로 지정해주면 쉽게 할 수 있지만 이것을 코드로 작성해야 할때는 어떻게 해야할까??


  • SceneDelegate의 scene 메소드에 코드를 작성한다.
    class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    
        var window: UIWindow?
    
        func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {}
    }

scene 메소드에 기본적으로 달려있는 주석을 읽어보자.

  • Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
  • If using a storyboard, the `window` property will automatically be initialized and attached to the scene.

번역해보면 scene메소드는 UIWindow 객체인 'window' 프로퍼티를 제공된 UIWindowScene 객체인 'scene'과 연결하고 그것을 설정할때 사용하라고 나와있다. 추가적으로 스토리보드를 사용하면 'window' 프로퍼티는 자동적으로 'scene'과 연결되어 시작된다고 한다.

 

즉, UIWindowScene 객체는 하나 이상의 UIWindow 객체를 관리하므로 scene 메소드 안에서 window 프로퍼티를 설정할 수 있고 그것을 scene과 연결할 수 있다. 우리는 이 window 프로퍼티를 통해 네비게이션 컨트롤러의 뷰를 보여줄 수 있다.

 

  • Navigation Controller를 window 프로퍼티와 연결
guard let scene = (scene as? UIWindowScene) else { return }
        window = UIWindow(frame: scene.coordinateSpace.bounds)
        window?.windowScene = scene
        
        let rootViewController = ViewController()
        let navigationController = UINavigationController(rootViewController: rootViewController)
        
        window?.rootViewController = navigationController
        window?.makeKeyAndVisible()
  1. window 프로퍼티에 주어진 scene의 크기와 동일한 UIWindow의 인스턴스를 생성하고 scene과 연결한다.
  2. 루트 뷰 컨트롤러가 될 뷰 컨트롤러의 인스턴스를 생성하고 네비게이션 컨트롤러와 연결해준다.
  3. window의 루트 뷰 컨트롤러로 네비게이션 컨트롤러를 설정해주고 window를 보여주는 makeKeyAndVisible 메소드를 호출한다.