SwiftUI mysterious space on top of the VStack

Viewed 792

I have this code

    NavigationView{
      VStack{
        GeometryReader{ geometry in
            VStack{
                Text("a")
            }
            .frame(width:geometry.size.width)
            .background(Color.orange)
            Spacer()
        }
      }
      .modifier(NavBarModifier(font: self.fontUI,text: "Profile"))
    }
    .navigationViewStyle(StackNavigationViewStyle())

I want the GeometryReader to appear at top of the VStack, however what I get is:enter image description here

Where the blue line is the top of the VStack and orange is the GeometryReader. I tried adding Spacer() after the GeometryReader, but it didn't work. How can I remove that spacing?

struct NavBarModifier: ViewModifier{
    var font: UIFont
    var text: String
    func body(content: Content) -> some View {
        return content
        .zIndex(0)
        .animation(.spring())
        .padding(.top,80)
        .navigationBarTitle(Text(self.text),displayMode: .inline)
        .navigationBarHidden(false)
        .foregroundColor(.orange)
        .background(NavigationConfigurator { nc in
                       nc.navigationBar.barTintColor = UIColor(red: 243/255, green: 107/255, blue: 21/255, alpha: 1)
                       nc.navigationBar.titleTextAttributes = [
                        .foregroundColor : UIColor.white,
                        .font : self.font,
                        .kern: 1.2
                       ]
        }
        .padding([.top, .leading, .trailing]))
    }
}
2 Answers

Just remove redundant padding in NavBarModifier

func body(content: Content) -> some View {
    return content
    .zIndex(0)
    .animation(.spring())
//    .padding(.top,80)        // << this one !!

You need to add the Spacer after the GeometryReader for it to layout in the top of the VStack and also add .edgesIgnoringSafeArea(.top) for it to ignore that white space (the safe area) and make it align at the top of the VStack.

VStack {
    GeometryReader{ geometry in
        VStack {
            Text("s")
        }
        .frame(width:geometry.size.width)
        .background(Color.orange)

        Spacer()
    }
    .edgesIgnoringSafeArea(.top)

    Spacer()
}
Related