Cannot make my status bar color to match my UINavigationBar color in SiwftUI

253 views Asked by At

My problem appears to be a simple one. But I just spent hours looking for a solution! I just have to make the status bar's background color conform to my UINavigationBar background's color (red in this sample).

Status bar color is not conform to the NavigationBar's color

I wrote a minimal code sample to reproduce my problem and help you for giving me a solution...

TestApp.swift

import SwiftUI

@main
struct TestApp: App {
    @Environment(\.scenePhase) private var phase

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .onChange(of: phase) { newPhase in
            switch newPhase {
            case .active:
                UINavigationBar.appearance().backgroundColor = UIColor.red
                break
            default:
                break
            }
        }
    }
}

ContentView.swift

struct DetailView1: View {

    var body: some View {
        Text("Detail view 1")
    }
}

struct ContentView: View {
    @State private var isDisplayDetailView1 = true

    var body: some View {
        NavigationView {
            List {
                Section {
                    NavigationLink(destination: DetailView1(), isActive: $isDisplayDetailView1) {
                        Text("Go to detail view 1")
                    }
                }
            }
            .navigationBarTitle("Menu")
            .listStyle(GroupedListStyle())
        
            DetailView1()
        }
    }
}

Obviously, I tried to add edgesIgnoringSafeArea(.top) to my NavigationView view (and to the List one, and to the DetailView1 one,...), but it doesn't change anything... Please help me, I don't understand where is the problem!

1

There are 1 answers

3
lorem ipsum On

Is there a reason you are using ScenePhase

You can just add this code at file scope

extension UINavigationController {
    override open func viewDidLoad() {
        super.viewDidLoad()
        
        let standard = UINavigationBarAppearance()
        standard.backgroundColor = .blue
        
        let compact = UINavigationBarAppearance()
        compact.backgroundColor = .green
        
        let scrollEdge = UINavigationBarAppearance()
        scrollEdge.backgroundColor = .red
        
        navigationBar.standardAppearance = standard
        navigationBar.compactAppearance = compact
        navigationBar.scrollEdgeAppearance = scrollEdge
    }
}