พื้นที่ลึกลับของ SwiftUI ที่ด้านบนของ VStack

Aug 20 2020

ฉันมีรหัสนี้

    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 แต่สิ่งที่ฉันได้รับคือ:

โดยที่เส้นสีน้ำเงินอยู่ด้านบนของ VStack และสีส้มคือ GeometryReader ฉันพยายามเพิ่ม Spacer () หลัง GeometryReader แต่ไม่ได้ผล ฉันจะลบระยะห่างนั้นได้อย่างไร

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

คำตอบ

1 Asperi Aug 20 2020 at 16:32

เพียงแค่ลบช่องว่างภายในที่ซ้ำซ้อนออก 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

คุณต้องเพิ่มตัวเว้นวรรคหลัง GeometryReader เพื่อให้มันจัดวางที่ด้านบนของVStackและเพิ่ม.edgesIgnoringSafeArea(.top)เพื่อให้ไม่สนใจช่องว่างนั้น (พื้นที่ปลอดภัย) และทำให้มันอยู่ในแนวเดียวกันที่ด้านบนของไฟล์VStack.

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

        Spacer()
    }
    .edgesIgnoringSafeArea(.top)

    Spacer()
}