Bart van Kuik
Bart van Kuik

Reputation: 4862

SwiftUI form section title and rows have incorrect formatting

The following SwiftUI form will render the section its header and contents incorrectly. The section header should be capitalized and have a background color. The rows should be marked up like a list, meaning, they should have list separators and padding.

struct ContentView: View {
    var body: some View {
        NavigationView {
            Form {
                Section(header: Text("Test")) {
                    ForEach(0..<5) { index in
                        Text("Row \(index)")
                    }
                }
                .navigationBarItems(trailing: Button(action: {}, label: { Text("Dummy") }))
            }
            .navigationTitle(Text("Navigation title"))
        }
    }
}

Result:

Incorrectly rendered section header and rows

Upvotes: 1

Views: 3217

Answers (1)

Bart van Kuik
Bart van Kuik

Reputation: 4862

The cause of the incorrect formatting is that the .navigationBarItems should not be attached to the Section but instead moved lower, to the Form:

Form {
    Section(header: Text("Test")) {
        ForEach(0..<5) { index in
            Text("Row \(index)")
        }
    }
}
.navigationBarItems(trailing: Button(action: {}, label: { Text("Dummy") }))
.navigationTitle(Text("Navigation title"))

This renders the form correctly:

Correctly rendered form

If you use the newer .toolbar modifier and attach it to the Section, the section will render correctly but the button simply won't show up. However .toolbar is only usable from iOS 14 and up.

Upvotes: 3

Related Questions