Search code examples
listswiftuiheaderalignmentsections

Left- or Center-Justifying Multiline Section Header for List in SwiftUI


Here is my code:

struct ContentView: View {

    var body: some View {
        Form {
            Section(header:
                VStack {
                    Text("Header line 1")
                    Text("This is header line 2")
            }) {
                List {
                    Text("Item 1")
                    Text("Item 2")
                    Text("Item 3")
                    Text("Item 4")
                }
            }
        }
    }
}

The issue is that I can't get both lines of the section header to justify or align in the same way. I'd prefer them both to be left-justified, but I would settle for them both to be centered to the screen as well. As it is, the alignment is strange, as shown below:

Odd Text Alignment

Any suggestions would be greatly appreciated.


Solution

  • Add VStack alignment

    Section(header:
        VStack(alignment: .leading) { //<< here alignment
            Text("Header line 1")
            Text("This is header line 2")
    }) 
    

    enter image description here