3

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)
}
pkamb
  • 30,595
  • 22
  • 143
  • 179
squarehippo10
  • 1,715
  • 1
  • 12
  • 37
  • Does this answer your question https://stackoverflow.com/a/63276688/12299030? – Asperi Sep 29 '20 at 15:30
  • I think it might get the job done, thank you, but I'm really hoping that I can figure this one out in a way that's similar to the example. – squarehippo10 Sep 30 '20 at 00:26

1 Answers1

2

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()
Asperi
  • 173,274
  • 14
  • 284
  • 455
  • I ended up going in a different direction, but this looks exactly like what I was trying to figure out. I'm sure it will be useful very soon. Thanks! – squarehippo10 Oct 01 '20 at 20:39