SwiftUI UINavigationBar does not ignore the top safe area. How to get rid of empty space on the top?

1.9k views Asked by At

enter image description here

Code I used to create an example of this navigation bar:

struct ContentView: View {
    init() {
        let defaultAppearance = UINavigationBarAppearance()
        defaultAppearance.configureWithOpaqueBackground()
        defaultAppearance.backgroundColor = .red

        UINavigationBar.appearance().standardAppearance = defaultAppearance
        UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)
    }

    var body: some View {
        ParentView()
    }
}

struct ParentView: View {
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(destination: DetailView()) {
                    Text("Tap here")
                }
            }
            .navigationBarTitle("", displayMode: .inline)
            .navigationBarHidden(true)
            .edgesIgnoringSafeArea(.all)
        }
    }
}

struct DetailView: View {
    var body: some View {
        VStack {
            Text("Detail View")
        }
        .edgesIgnoringSafeArea(.all)
   }
}

It doesn't matter where I'm putting .edgesIgnoringSafeArea(.all) it doesn't work. Is there another way to tell Navigation Bar to ignore the safe area?

If it's not the safe area problem, then I need to make the whole navigation bar to have the same height of UINavigationBarContentView displayed in UI Hierarchy: enter image description here

1

There are 1 answers

0
Mary X On

I'm unsure if you still need help with this but in iOS 16.0+ you can instead apply .ignoresSafeArea() in all the places you have invoked edgesIgnoringSafeArea(.all). Then add the following code to your initializer in order to apply a custom background color to the entire navigation bar, including the safe area:

let defaultAppearance = UINavigationBarAppearance()
defaultAppearance.configureWithDefaultBackground()
defaultAppearance.backgroundColor = .red
UINavigationBar.appearance().scrollEdgeAppearance = defaultAppearance