【问题标题】:How to change status bar color of a specific view in SwiftUI App Life Cycle?如何在 SwiftUI 应用程序生命周期中更改特定视图的状态栏颜色?
【发布时间】:2021-09-18 22:13:51
【问题描述】:

我在这里尝试了解决方案:SwiftUI: Set Status Bar Color For a Specific View 和这里:SwiftUI: Set Status Bar Color For a Specific View

这两个解决方案都使用了 SceneDelegate,这在 SwiftUI 2/3 中显然不存在。理想情况下,我希望为特定视图更改颜色。它可能是它们在这些帖子中显示的修饰符,也可能是基于我在称为 AppState 的 Swift 类中的值:

class AppState: NSObject, ObservableObject {
  @Published var currentScreen: Screens = .view1
}

enum Screens {
  case view1
  case view2
  case view3
}

在这种情况下,我想让“view2”有一个白色状态栏,但不知道该怎么做——非常感谢任何帮助!

更新:

在我的代码中,我有一个带有 Color.black 的堆栈,该堆栈在此特定视图上具有 .edgesIgnoringSafeArea(.all) 属性,但没有其他属性,因此我需要在此视图中将文本设为白色,但在其他视图中设为黑色...

【问题讨论】:

  • @RajaKishan 我并没有尝试更改状态栏的背景,而是尝试更改实际文本/图像的颜色(也就是时间、位置/wifi/电池)使用图标为不同的颜色,但仅限于一个特定的视图)
  • 您找到解决方案了吗?我有同样的问题

标签: swift xcode swiftui statusbar


【解决方案1】:

您可以更改preferredColorScheme,但这会更改View 的整个方案,而不仅仅是状态栏。字体和背景也会切换。

struct CustomStatusBarView: View {
    @StateObject var appState: AppState = AppState()
    var body: some View {
        ZStack{
            Color.gray.ignoresSafeArea()
            VStack{
                switch appState.currentScreen{
                    
                case .view1:
                    Text("view 1")
                case .view2:
                    Text("view 1").preferredColorScheme(.dark)
                case .view3:
                    Text("view 1")
                }
                Button("change view", action: {
                    appState.currentScreen = Screens.allCases.randomElement()!
                })
            }
        }
    }
}

【讨论】:

  • 我尝试将 .preferredColorScheme(.dark) 修饰符添加到 ContentView 中的最外层视图,但它仍然只更改手机安全区域内的内容(也就是它不会更改内容的文本颜色在状态栏中)。我在整个应用程序中没有其他 colorScheme 修饰符......另外,我想使用 .colorScheme(.dark) 代替,因为我需要强制状态栏中的文本为白色,但这不会改变任何东西: /
【解决方案2】:

请尝试将以下键添加到 Info.plist 文件中

<key>UIViewControllerBasedStatusBarAppearance</key> 
<true/>

【讨论】:

    猜你喜欢
    • 2020-11-15
    • 1970-01-01
    • 2022-11-11
    • 2015-09-29
    • 2020-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多