Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")
                    }
                }
            }
        }  
    }
}
like image 998
Kenan Nur Avatar asked Jan 26 '26 21:01

Kenan Nur


1 Answers

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
        }
    }
}
like image 138
Raja Kishan Avatar answered Jan 28 '26 16:01

Raja Kishan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!