swiftuieditmode

How to use the EditButton in SwiftUI?


I used the sample code of Apple. However I can toggle the EditMode button all I want, but it won't update the Form accordingly. Is this a bug or am I not using it right?

struct ContentView: View {
    @Environment(\.editMode) private var editMode
    @State private var name = "Maria Ruiz"

    var body: some View {
        NavigationStack {
            Form {
                if editMode?.wrappedValue.isEditing == true {
                    TextField("Name", text: $name)
                        .background(.blue)
                } else {
                    Text(name)
                        .background(.red)
                }
            }
            .animation(nil, value: editMode?.wrappedValue)
            .toolbar {
                EditButton()
            }
        }
    }
}

Solution

  • This seems to be similar to the behaviour of isSearching - you should read the environment value in a view that is being edited (a view inside the Form).

    Example:

    struct ContentView: View {
        var body: some View {
            NavigationStack {
                Form {
                    SubView()
                }
                .toolbar {
                    EditButton()
                }
            }
        }
    }
    
    struct SubView: View {
        @Environment(\.editMode) private var editMode
        @State private var name = "Maria Ruiz"
    
        var body: some View {
            Group {
                if editMode?.wrappedValue.isEditing == true {
                    TextField("Name", text: $name)
                        .background(.blue)
                } else {
                    Text(name)
                        .background(.red)
                }
            }
        }
    }