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()
)
}
}
}
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")
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With