如何在列表中编辑行

如何在列表中编辑行

本文介绍了SwiftUI - 如何在列表中编辑行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

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

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

您需要小心,并确保 .environment(\.editMode, self.$isEditMode) 位于 .navigationBarItems(trailing: E​​ditButton()) 之后.

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

这篇关于SwiftUI - 如何在列表中编辑行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 05:05