Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI - How do I make edit rows in a list?

I'd like to use the EditButton() to toggle edit mode, and have my list rows switch to edit mode. I want to include a new button in edit mode for opening a modal. I can't even get the EditMode value to switch the row content at all.

struct ContentView: View {

    @Environment(\.editMode) var isEditMode

    var sampleData = ["Hello", "This is a row", "So is this"]

    var body: some View {
        NavigationView {

            List(sampleData, id: \.self) { rowValue in
                if (self.isEditMode?.value == .active) {
                    Text("now is edit mode")  // this is never displayed
                } else  {
                    Text(rowValue)
                }
            }
            .navigationBarTitle(Text("Edit A Table?"), displayMode: .inline)
            .navigationBarItems(trailing:
                EditButton()
            )
        }
    }
}
like image 923
radicalappdev Avatar asked Aug 14 '19 14:08

radicalappdev


2 Answers

You need to set the environment value for editMode in the List:

struct ContentView: View {
    @State var isEditMode: EditMode = .inactive

    var sampleData = ["Hello", "This is a row", "So is this"]

    var body: some View {
        NavigationView {
            List(sampleData, id: \.self) { rowValue in
                if (self.isEditMode == .active) {
                    Text("now is edit mode")
                } else  {
                    Text(rowValue)
                }
            }
            .navigationBarTitle(Text("Edit A Table?"), displayMode: .inline)
            .navigationBarItems(trailing: EditButton())
            .environment(\.editMode, self.$isEditMode)
        }
    }
}

You need to be careful, and make sure .environment(\.editMode, self.$isEditMode) comes after .navigationBarItems(trailing: EditButton()).

like image 112
kontiki Avatar answered Sep 20 '22 14:09

kontiki


Adding to @kontiki answer, if you prefer using a boolean value for editMode so it is easier to modify, use this @State variable:

@State var editMode: Bool = false

And modify the .environment modifier to this:

.environment(\.editMode, .constant(self.editMode ? EditMode.active : EditMode.inactive))

Now switching to/from edit mode with your own button is as easy as:

Button(action: {
    self.editMode = !self.editMode
}, label: {
    Text(!self.editMode ? "Edit" : "Done")
})
like image 30
kdion4891 Avatar answered Sep 22 '22 14:09

kdion4891