SwiftUI位于VStack顶部的神秘空间

时间:2020-08-20 08:43:47

标签: swiftui

我有这个代码

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

我想要 GeometryReader出现在VStack的顶部,但是我得到的是:enter image description here

蓝线是VStack的顶部,橙色是GeometryReader。我尝试在GeometryReader之后添加Spacer(),但是没有用。如何删除该间距?

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 个答案:

答案 0 :(得分:1)

只需删除NavBarModifier中的多余填充

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

答案 1 :(得分:0)

您需要在GeometryReader之后添加垫片,以使其在VStack的顶部布局,还需要添加.edgesIgnoringSafeArea(.top)以便忽略该空白(安全区域)并使之对齐在VStack的顶部。

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

        Spacer()
    }
    .edgesIgnoringSafeArea(.top)

    Spacer()
}