如何在 SwiftUI 中检查 EditButton/EditMode 状态

How to check EditButton/EditMode state in SwiftUI

我有以下测试代码。但是当点击编辑按钮时,文本不会改变。我找不到任何相关信息。如何check/control 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")
                    }
                }
            }
        }  
    }
}

您可以通过将 .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
        }
    }
}