简体   繁体   English

如何更改 swiftUI iOS 中的状态栏文本颜色

[英]How to change the status bar text color in swiftUI iOS

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:您好:) 我正在尝试在应用程序加载时将状态栏的文本颜色设置为浅色或深色,我使用的是SwiftUI而不是UIKit所以我没有任何花哨的ViewControllers ,这是我迄今为止尝试过的:

In my Test_applicationApp file:在我的Test_applicationApp文件中:

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:发生这种情况的是,如果我处于浅色主题中,则文本颜色会像这样变暗:

在此处输入图像描述

(This is on a iPhone 8, version 15.6.1) (这是在 iPhone 8 版本 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任何帮助将不胜感激,此外,如果您对此问题感到困惑或需要更多详细信息,请随时联系我,因为时间已晚,我并没有完美地写出这个问题,我不得不输入赶时间XD

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:)强调.preferredColorScheme(.light) ,如果需要,您也可以将其更改为.preferredColorScheme(.dark) :)

Hope this helps someone else like future me who forgets the fix for this XD希望这可以帮助像未来我这样忘记修复此 XD 的其他人

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM