I created an application in SwiftUI.
Views are structs, but I need to know the View Controller because it is needed for presenting some special alerts.
I see that in my project there are AppDelegate, and SceneDelegate.
I found this
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
So I want to pass the View Controller reference to the other Views.
Is window.rootViewController the right value to pass and use?
The possible solution is to inject hosting view controller as environment key, so it can be available at any
ContentViewinternal hierarchy level.Here is a demo. Tested with Xcode 12 / iOS 14.
ContentView