How To: Programmatically Change iOS Status Bar Color with SwiftUI
With UIKit, changing the color of the status bar content is as simple as:
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 SceneDelegate.swift
:
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 UIHostingController
:
Now in 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 changeStatusBarStyle
?
In SceneDelegate
, recall that we made ContentHostingController
the 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!