[SwiftUI] Implementation method equivalent to changing UIWindow.rootViewController

I've used UIKit to replace UIWindow.rootViewController. How to implement it in SwiftUI? I had a question, so I looked it up.

environment

When using the Swift UI lifecycle of iOS 14 or later. In Xcode12, when creating a project, you can select Swift UI App and UIKit App Delegate as Life Cycle, but if you select the former.

How to switch equivalent to rootViewController

Implement as follows.

@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)
            }
        }
    }
}

The point is that it is surrounded by WindowGroup and switched by index. You can switch to SecondView by changing the index in ContentView.

I checked using View Hierarchy of Xcode, but it was a change equivalent to rootViewController.

reference

https://stackoverflow.com/questions/58104813/change-the-root-view-of-uihostingcontroller-in-swiftui → I used this method

https://qiita.com/Pman5151/items/0c079e2c79f132597ef9 → It is different from this method, but I used it as a reference.

Recommended Posts

[SwiftUI] Implementation method equivalent to changing UIWindow.rootViewController
Method to search
16 Corresponds to method invocation