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
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)
}
}