Unfortunately, it took quite a bit of searching (and some help from this StackOverflow question) to find a suitable solution for SwiftUI. Let’s get started!
First, let’s understand how SwiftUI views are attached in
We see that the root SwiftUI view,
ContentView is attached to a single
UIHostingController, which is the root view controller of the key window.
The key to programmatically changing the status bar color is to create our own implementation of
SceneDelegate.swift, we can simply use
ContentHostingController instead of
UIHostingController. But how do we retrieve the
ContentHostingController in a SwiftUI view, so that we can call
SceneDelegate, recall that we made
rootViewController of our key window. We can then declare an extension on
UIApplication to access these properties:
Nice! Now all we need to do in a view is something like the following:
And that’s it!