13

我想使用 EditButton() 来切换编辑模式,并让我的列表行切换到编辑模式。我想在编辑模式中包含一个新按钮以打开模式。我什至无法获得 EditMode 值来切换行内容。

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

2 回答 2

23

您需要在 List 中为 editMode 设置环境值:

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

您需要小心,并确保.environment(\.editMode, self.$isEditMode).navigationBarItems(trailing: EditButton()).

于 2019-08-14T16:06:15.267 回答
4

添加到@kontiki 答案,如果您更喜欢为 editMode 使用布尔值以便更容易修改,请使用此@State变量:

@State var editMode: Bool = false

并将.environment修饰符修改为:

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

现在使用您自己的按钮切换到/从编辑模式非常简单:

Button(action: {
    self.editMode = !self.editMode
}, label: {
    Text(!self.editMode ? "Edit" : "Done")
})
于 2019-11-10T20:43:40.970 回答