[iOS] rootViewController 변경하는 방법

z-wook·2024년 1월 22일
post-thumbnail

SceneDelegate에서 변경하는 방법

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 }
        window = UIWindow(windowScene: windowScene)
        window?.rootViewController = HomeViewController() // rootView로 변경하고자 하는 ViewController
        window?.makeKeyAndVisible()
    }
}

View에서 변경하는 방법

rootView의 변경을 시도하는 곳이 UIView를 상속한 class라면 해당 view의 window 속성을 통해 rootView를 변경할 수 있습니다.

self.view.window?.rootViewController = HomeViewController()

다른 방법

  1. deprecated된 방법
UIApplication.shared.windows.first?.rootViewController = HomeViewController() 
  1. 대체 방법
if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
   let window = windowScene.windows.first(where: { $0.isKeyWindow }) {
	window.rootViewController = HomeViewController()
}
profile
🍎 iOS Developer

0개의 댓글