1

I want to add the possibility to select items in a list when edit mode is selected, additionally to the delete and move option. Ideally I want to use the existing edit, delete and move buttons instead of writing my own. I tried the example from the documentation. It's not working for me. The value of editMode is always .inactive. I'm using XCode 14. The deployment target of my app is iOS 16.0.

This is my source code:

import SwiftUI

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

    var body: some View {
        NavigationView {
            Form {
                if editMode?.wrappedValue.isEditing == true {
                    TextField("Name", text: $name)
                } else {
                    Text("test")
                }
            }
            .animation(nil, value: editMode?.wrappedValue)
            .toolbar { // Assumes embedding this view in a NavigationView.
                EditButton()
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
    }
}

It always shows the test text. I also tried a variant with the .onChange modifier, with the same result.

1 Answers1

0

Forwarding the fix from https://developer.apple.com/forums/thread/716434:

Try extracting the parts that access the editMode property from the container that changes based on it, like List/Form.

struct ContentView: View {

    var body: some View {
        NavigationView {
            Form {
                MyForm()
                
            }
            .toolbar { // Assumes embedding this view in a NavigationView.
                EditButton()
            }
        }
    }
}

and

struct MyForm: View {
    @Environment(\.editMode)
    private var editMode
    
    @State
    private var name = "Maria Ruiz"
    
    var body: some View {
        Text(String(editMode!.wrappedValue.isEditing))
        
        if editMode?.wrappedValue.isEditing == true {
            TextField("Name", text: $name)
        } else {
            Text("test")
        }
    }
}