SwiftUI - Using @main to set the rootViewController

259 views Asked by At

When using the SceneDelegate in SwiftUI, it was possible to create a function like the one below that could be used to set the view as shown here. However, in the latest version we now use a WindowsGroup. Is it possible to write a function that changes the view in the WindowsGroup?

func toContentView() {
   let contentView = ContentView()
      window?.rootViewController = UIHostingController(rootView: contentView)
}
1

There are 1 answers

0
Asperi On BEST ANSWER

Here is possible alternate approach that do actually the same as your old toContentView

  1. helper class
class Resetter: ObservableObject {
    static let shared = Resetter()

    @Published private(set) var contentID = UUID()

    func toContentView() {
        contentID = UUID()
    }
}
  1. content of @main
    @StateObject var resetter = Resetter.shared
    var body: some Scene {
        WindowGroup {
            ContentView()
               .id(resetter.contentID)
        }
    }
  1. now from anywhere in code to reset to ContentView you can just call
Resetter.shared.toContentView()