Development/iOS

[iOS] Storyboard 없이 코드로 UIWindow.rootViewController 설정하기

EUNJI HA 2022. 3. 10. 13:04

Xcode의 프로젝트를 생성하면 다음과 같이 Interface로 SwiftUI or Storyboard를 선택할 수 있다. 

Interface > Storyboard로 설정하는 프로젝트에는 기본적으로 Main.storyboard와 ViewController.swift 파일이 생성되고 Info.plist에는 Main.storyboard를 연결해주는 설정이 있다.

[Info.plist]에 설정되어 있는 Main.storyboard
[Main.storyboard] 의 루트 뷰컨트롤러로 ViewController.swift가 연결되어 있다.

만일, Storyboard를 사용하지 않고 코드로만 rootViewController를 설정해주고 싶다면 다음을 살펴보시라.

 

1. Main.storyboard와 ViewController.swift 파일 지우기

2. Info.plist에서 Main.storyboard 설정 제거 

3. 새로운 [New]ViewController.swift 파일 만들기

4. SceneDelegate.swift에서 3에서 만든 [New]ViewController.swift 파일을 rootViewController로 연결하기

 

초기의 SceneDelegate.swift

 

import UIKit

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?


    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    
        guard let _ = (scene as? UIWindowScene) else { return }
    }
    
    ...
}
// 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.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).

 

 

 

수정된 SceneDelegate.swift

다음 코드는 UINavigationController > MainViewController 를 UIWindow의 rootViewController로 설정하는 코드이다.

import UIKit

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 }
        self.window = UIWindow(windowScene: windowScene)
        
        let rootViewController = MainViewController() // 본인이 만든 ViewController
        let rootNavigationViewController = UINavigationController(rootViewController: rootViewController)
        
        self.window?.rootViewController = rootNavigationViewController
        self.window?.makeKeyAndVisible()
    }
    
    ...
    
}