the.blaggy
the.blaggy

Reputation: 895

SwiftUI Life Cycle App: How to change Status Bar Color

Is there a way to change the status bar color if using the new app life cycle?

I know that for UIKit life cycle there is the workaround where you create your own HostingController to overwrite the color. But the new SwiftUI life cycle isn't using a UIHostingController at all.

Upvotes: 2

Views: 490

Answers (1)

pawello2222
pawello2222

Reputation: 54641

Here is a possible workaround:

@main
struct TestApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView() // or any other loading view
                .onAppear(perform: UIApplication.shared.switchHostingController)
        }
    }
}

class HostingController: UIHostingController<ContentView> {
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
}

extension UIApplication {
    func switchHostingController() {
        windows.first?.rootViewController = HostingController(rootView: ContentView())
    }
}

Two drawbacks I noticed:

  • the status bar style is switched in .onAppear - there might be a split second when you see the previous style
  • the ContentView will be created twice at the beginning

Upvotes: 3

Related Questions