Gerd Castan
Gerd Castan

Reputation: 6849

SwiftUI: edit List inside of a Section

Without Form and Section, I can edit a list:

var body: some View {
            List {
                ForEach(modeConfigurations.sorted, id: \.id) { item in
                    Text("\(item.defaultSortIndex)")
                }
                .onMove(perform: move)
            }
            .navigationBarItems(trailing:
                   EditButton()
            )
} // Body

enter image description here

I'd like to edit inside a Section of a Form, but it doesn't work there:

var body: some View {
    Form{
        Section(header: Text("Sort")){
            List {
                ForEach(modeConfigurations.sorted, id: \.id) { item in
                    Text("\(item.defaultSortIndex)")
                }
                .onMove(perform: move)
            }
            .navigationBarItems(trailing:
                   EditButton()
            )
        } // Sort Section
    } // Form
} // Body

I can't edit and the Text inside ForEach is not rendered as separate line.

enter image description here

How can I edit a List inside a Section of a Form?

Upvotes: 0

Views: 1707

Answers (1)

Mojtaba Hosseini
Mojtaba Hosseini

Reputation: 119360

You should put .navigationBarItems(trailing: EditButton()) on the Form instead to make it work.

Also List is not needed as Section already "acts like" a List. (Thanks to @Sweeper for mentioning that)

var body: some View {
    Form {
        Section(header: Text("Sort")) {
            // List { // <- This is not needed as Section contains an implicit list.
                ForEach(modeConfigurations.sorted, id: \.id) { item in
                    Text("\(item.defaultSortIndex)")
                }
                .onMove(perform: move)
            // } // <- Removeed this as we removed `List`
        } // Sort Section
    } // Form
    .navigationBarItems(trailing: EditButton()) // <- Misplacing this was the issue.
} // Body

Upvotes: 2

Related Questions