swiftswiftuienvironment-variableseditmode

How to check EditButton/EditMode state in SwiftUI


I have the following test codes. But when Edit button tapped Text doesn't change. I could not find anything about that. How to check/control editButton/editMode state changes?

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

Solution

  • You can achieve this by setting .environment with @State mode.

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