iosswiftswiftui

How to eliminate the space above Section in SwiftUI Form?


I wanna eliminate the space above the first Section in a Form

enter image description here

 var body: some View {
        VStack {
            Text("Text 1")
            Form {
                Section {
                    Text("Text 2")
                }
            }
        }
    }

I tried to set the frame of the Section's header to 0, but it does not work


Solution

  • The solution is to add a Section with an EmptyView(), and then put the view you want at the top inside the Section's header.

    var body: some View {
        VStack {
            Text("Text 1")
    
            Form {
                Section(header: VStack(alignment: .center, spacing: 0) {
                    Text("Text 2")
                        .padding(.all, 16)
                        .frame(width: UIScreen.main.bounds.width, alignment: .leading)
                        .background(Color.white)
                }) {
                    EmptyView()
                }.padding(.top, -6)
            }
        }
    }