SwiftUI delete rows from a list

后端 未结 1 1200
醉梦人生
醉梦人生 2021-01-23 07:03

As you can see from the image I have a list of colors, I would like to be able to also give the possibility to delete a color from the array.

I tried

相关标签:
1条回答
  • 2021-01-23 07:43

    The problem is that in your List, the id you give it is \.offset. However, since you are removing data from bgColors, so this data can change. Instead, you should set the id as \.element because it will be constant for each color.

    Consider this simplified example, which crashes when you remove a Color from the list:

    struct ContentView: View {
        
        @State private var arr: [Color] = [.red, .green, .blue]
    
        var body: some View {
            List {
                ForEach(Array(arr.enumerated()), id: \.offset) { (index, _) in
                    ColorPicker("Color", selection: $arr[index])
                }
                .onDelete(perform: delete)
            }
        }
        
        private func delete(at offsets: IndexSet) {
            arr.remove(atOffsets: offsets)
        }
    }
    

    And the working example, where the changes are the id given to the List, and the new Binding to the color:

    struct ContentView: View {
    
        @State private var arr: [Color] = [.red, .green, .blue]
    
        var body: some View {
            List {
                ForEach(Array(arr.enumerated()), id: \.element) { (index, _) in
                    ColorPicker(
                        "Color",
                        selection: Binding<Color>(
                            get: { arr[index] },
                            set: { arr[index] = $0 }
                        )
                    )
                }
                .onDelete(perform: delete)
            }
        }
    
        private func delete(at offsets: IndexSet) {
            arr.remove(atOffsets: offsets)
        }
    }
    
    0 讨论(0)
提交回复
热议问题