swiftswiftui

How do you use selection in a List when it has a foreach in inside it


I had a list that was bound to a selection that was working as intended:

@State private var selection: ExerciseName?

List(exercisesNames,id: \.self, selection: $selection)  { exerciseName in
     Text(exerciseName.name)     
}

but I needed to add onDelete functionality so I had to make a ForEach in the list but the problem is now the selection not longer works?

List(selection: $selection) {
    ForEach(exercisesNames) { exerciseName in
        Text(exerciseName.name)
    }
    .onDelete(perform: delete)
}

Solution

  • Since you used id: \.self in your first code snippet, you should do that in ForEach too.

    ForEach(exercisesNames, id: \.self) { ... }
    

    List selection is based on the tags of the list rows. The id: parameter (of either List.init or ForEach.init) automatically uses the key path passed to it as the tag. On the other hand, ForEach without an id: parameter uses the elements' id property as the tag.