Murad Shahmammadli
Murad Shahmammadli

Reputation: 187

SwiftUI mysterious space on top of the VStack

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]))
    }
}

Upvotes: 3

Views: 1844

Answers (2)

iPile
iPile

Reputation: 24

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()
}

Upvotes: 0

Asperi
Asperi

Reputation: 257711

Just remove redundant padding in NavBarModifier

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

Upvotes: 1

Related Questions