首页 > 解决方案 > 更改状态栏颜色 SwiftUI 没有 UIHosting

问题描述

我正在尝试动态更改状态栏颜色但没有成功,有人知道如何更改吗?我没有使用 UIHosting 控制器,因此没有完全使用 swiftUI 的 AppDelegate 或 SceneDelegate:

@main
struct MyProjectApp: App{}

如果我设置ZStack {}.preferredColorScheme(.light)它只应用一次,那么如果我转到另一个视图并尝试放置ZStack {}.preferredColorScheme(.dark)它不起作用。

我想我已经在 stackoverflow 上尝试了所有问题,所以如果有人有明确的解决方案,我将不胜感激。

@更新的代码示例

struct ContentA: View {
    var body: some View {
        NavigationView {
            ZStack {
                NavigationLink(destination: ContentB()) {
                    Text("Show Detail View")
                }.navigationBarTitle("Navigation")
            }.preferredColorScheme(.light)
        }
    }
}
struct ContentB: View {
    var body: some View {
        ZStack {
            Text("Hello ContetB")
                .padding()
                .foregroundColor(.green)
        }.preferredColorScheme(.dark)
    }
}

如果您尝试使用这种方式更改 StatusBar 颜色,则它不起作用。

标签: iosswiftswiftui

解决方案


应用程序中的颜色应该是自动动态的,除非您专门设置它们。您可以在 Previews 部分切换 .preferredColorScheme。

struct ContentView: View {
    var body: some View {
        Text("Hello, world!")
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
            .preferredColorScheme(.dark)
    }
}

推荐阅读