Sorin Lica
Sorin Lica

Reputation: 7636

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

Upvotes: 26

Views: 19221

Answers (5)

Mojtaba Hosseini
Mojtaba Hosseini

Reputation: 119380

iOS 17

You can remove the margin for any edge of any scrollable content with the .contentMargins modifier.

VStack {
    Text("Text 1")
    Form {
        Section {
        Text("Text 2")
    }
}
.contentMargins(.top, 0, for: .scrollContent) // 👈 this modifier

🎁 Other Padding / Margin / Spacings of Lists

There are several spacings that you can change in a list on all iOS versions.

You can change any of them using 👉 this answer here 👈

Demo

Upvotes: 2

Sorin Lica
Sorin Lica

Reputation: 7636

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

Upvotes: 8

Phantom59
Phantom59

Reputation: 1121

The best solution may depend on your requirements. What worked for me was an empty Text view as in:

  Section(header: Text("")) {
    MySectionView()
  }

BTW, I tried EmptyView() but that is ignored completely; as in the space still remains.

Upvotes: 1

anon
anon

Reputation:

I'd supply a dummy header view and set its size to be zero:

Section(header: Color.clear
                .frame(width: 0, height: 0)
                .accessibilityHidden(true)) {
  Text("Text 2")
}

Upvotes: 0

iphaaw
iphaaw

Reputation: 7204

This is much simpler:

struct ContentView: View 
{

    init() 
    {
        UITableView.appearance().tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: Double.leastNonzeroMagnitude))
    }

    var body: some View 
    {

    }
}

Upvotes: -4

Related Questions