SwiftUI - How do I make edit rows in a list?
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())
.
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")
})