How to change the status bar text color in swiftUI iOS

Viewed 23

Hi there :) I'm trying to set the status bar's text color to light or dark on app load, I'm using SwiftUI not UIKit so I don't have any fancy ViewControllers, here's what I've tried so far:

In my Test_applicationApp file:

import SwiftUI

@main
struct Test_applicationApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
extension UIApplication {
    func switchHostingController() -> Void {
        windows.first?.rootViewController = DarkHostingController(rootView: ContentView())
    }
}
class DarkHostingController<ContentView>: UIHostingController<ContentView> where ContentView : View {
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
}

ContentView:

import SwiftUI

struct ContentView: View {
    init() {
        UIApplication.shared.switchHostingController()
    }
    var body: some View {
        ZStack {
            ......
        }
    }
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

What happens with this is that if I'm in light theme, the text color is dark like so:

enter image description here

(This is on a iPhone 8, version 15.6.1)

Does anyone know how to do this? Any help whatsoever would be really appreciated! Also if you're confused or need any more details on this questions feel free to hit me up, I didn't exactly write this question perfectly since it's getting late and I had to type it out in a rush XD

1 Answers

The answer turned out to be as simple as this:

struct ContentView: View {
    init() {
        UIApplication.shared.switchHostingController()
    }
    var body: some View {
        ZStack {
            ......
        }.preferredColorScheme(.light)
    }
}

emphasis on the .preferredColorScheme(.light), you could also change it to .preferredColorScheme(.dark) too if you wanted :)

Hope this helps someone else like future me who forgets the fix for this XD

Related