skip to Main Content

I tried the solutions here: SwiftUI: Set Status Bar Color For a Specific View and here: SwiftUI: Set Status Bar Color For a Specific View

Both of these solutions utilize SceneDelegate, which obviously doesn’t exist in SwiftUI 2/3. Ideally, I’d like the color to change for a specific view. It could be a modifier as they show in those posts or it could be based on a value I have in a Swift class that I call AppState:

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

enum Screens {
  case view1
  case view2
  case view3
}

I’d like to make ‘view2’ in this case have a white status bar, not sure how to do this though–any help is much appreciated!

Update:

In my code, I have a Stack with a Color.black that has the .edgesIgnoringSafeArea(.all) property on this specific view but no others so I need to make the text white in this view, but black in the others…

Demo

2

Answers


  1. You can change the preferredColorScheme but this changes the whole scheme for the View not just the status bar. Fonts and backgrounds will switch too.

    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()!
                    })
                }
            }
        }
    }
    
    Login or Signup to reply.
  2. Please try adding the following key to the Info.plist file

    <key>UIViewControllerBasedStatusBarAppearance</key> 
    <true/>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search