EditMode not working in SwiftUI

EditMode is an object that switches edit mode active like a UITableView. If your code does not change to active edit mode, try this example.

struct Product: Hashable {
    var name: String
    var value: Int
}

struct ContentView: View {
    @State private var products = [
        Product(name: "Camera", value: 400),
        Product(name: "NoteBook", value: 2),
        Product(name: "Pen", value: 1),
    ]
    @State private var selectedProducts: Set< Product> = []
    @Environment(\.editMode) private var editMode

    var body: some View {
        List(selection: $selectedProducts) {
            ForEach(products, id: \.self) { product in
                Text(product.name)
            }
        }
        .environment(\.editMode, editMode)
    }
}

#Preview {
    ContentView()
}

If you write forEach without “id”, you need to put .tag on your element. (However, since selectedProducts requires Hashable, you should also consider that follow the way code above. Easier and more simple.)

// struct Product: Hashable {
struct Product: Identifiable, Hashable {
    var name: String
    var value: Int
}

// ForEach(products, id: \.self) { product in
ForEach(products) { product in
    // Text(product.name)
    Text(product.name).tag(product)
}


Posted

in