0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[SwiftUI]UIWindow.rootViewControllerの変更と同等な実装方法

Posted at

今までUIKitで、UIWindow.rootViewControllerを置き換えたりしたことがありました。
SwiftUIではどのように実装するのか?という疑問があったので、調べました。

環境

iOS14以降のSwiftUIライフサイクルを使う場合です。
Xcode12では、プロジェクトを作成する際、Life CycleとしてSwiftUI AppUIKit App Delegateが選べますが、前者を選んだ場合です。

rootViewController相当の切り替え方法

以下のように実装します。

@main
struct LaunchScreenTestApp: App {
    
    @State var index: Int = 0
    
    var body: some Scene {
        WindowGroup {
            if self.index == 0 {
                ContentView(index: self.$index)
            } else {
                SecondView(index: self.$index)
            }
        }
    }
}

ポイントは、WindowGroupで囲い、indexでスイッチしているところです。
ContentViewの中でindexを変える操作を行うことで、SecondViewに切り替わります。

XcodeのView Hierarchyを使って調べましたが、rootViewController相当の変更になっていました。

参考

https://stackoverflow.com/questions/58104813/change-the-root-view-of-uihostingcontroller-in-swiftui
→この方法を使いました

https://qiita.com/Pman5151/items/0c079e2c79f132597ef9
→この方法とは別ですが、参考にしました。

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?