SwiftUI không gian bí ẩn trên VStack

Aug 20 2020

Tôi có mã này

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

Tôi muốn GeometryReader xuất hiện ở đầu VStack, tuy nhiên những gì tôi nhận được là:

Trong đó đường màu xanh lam là trên cùng của VStack và màu cam là GeometryReader. Tôi đã thử thêm Spacer () sau GeometryReader, nhưng nó không hoạt động. Làm cách nào để loại bỏ khoảng cách đó?

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

Trả lời

1 Asperi Aug 20 2020 at 16:32

Chỉ cần loại bỏ phần đệm thừa trong NavBarModifier

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

ignalonzo Aug 20 2020 at 15:54

Bạn cần thêm Spacer sau GeometryReader để nó bố trí ở trên cùng VStackvà cũng thêm .edgesIgnoringSafeArea(.top)để nó bỏ qua khoảng trắng đó (vùng an toàn) và làm cho nó căn chỉnh ở trên cùng VStack.

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

        Spacer()
    }
    .edgesIgnoringSafeArea(.top)

    Spacer()
}