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

安稳与你 提交于 2020-01-13 20:34:06

问题


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()
            )
        }
    }
}

回答1:


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()).




回答2:


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")
})


来源:https://stackoverflow.com/questions/57496453/swiftui-how-do-i-make-edit-rows-in-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!