0

我有以下测试代码。但是当点击编辑按钮时,文本不会改变。我找不到任何相关信息。如何检查/控制 editButton/editMode 状态变化?

struct TestView: View {
    @State private var list = [1,2,3,4,5]
    @State private var selection = Set<Int>()
    @Environment(\.editMode) var mode
    
    var body: some View {
        NavigationView {
            List(selection: $selection) {
                ForEach(list, id: \.self) { item in
                    Text("\(item)")
                }
            }
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    EditButton()
                }
                ToolbarItem(placement: .navigationBarTrailing) {
                    if mode?.wrappedValue.isEditing ?? false {
                        Text("Editing")
                    } else {
                        Text("Not Editing")
                    }
                }
            }
        }  
    }
}
4

1 回答 1

2

.environment您可以通过设置@State模式来实现这一点。

struct TestView: View {
    @State private var list = [1,2,3,4,5]
    @State private var selection = Set<Int>()
    @State var mode: EditMode = .inactive //< -- Here
    
    var body: some View {
        NavigationView {
            List(selection: $selection) {
                ForEach(list, id: \.self) { item in
                    Text("\(item)")
                }
            }
            
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    EditButton()
                }
                ToolbarItem(placement: .navigationBarTrailing) {
                    Text(mode == .active ? "Editing" : "Not Editing")
                }
            }.environment(\.editMode, $mode) //< -- Here
        }
    }
}
于 2021-06-23T18:09:00.037 回答