Currently, I create a generic list as follows:
List {
ForEach(viewModel.categoryItems) { category in
Text("\(category.category)")
}.onMove { indexSet, newOffset in
viewModel.categoryItems.move(fromOffsets: indexSet, toOffset: newOffset)
}
}.toolbar {
ToolbarItem {
if viewModel.categoryItems.count > 0 {
EditButton()
}
}
}
I would like to be able to number this list and also have those numbers change on move (2 becomes 1 if moved into the 1 place).
CodePudding user response:
one option would be to use the indices
property of the array. Something like this:
struct ContentView: View {
@ObservedObject
var viewModel = Model()
var body: some View {
List {
ForEach(viewModel.categoryItems.indices, id: \.self) { idx in
Text("\(idx) - \(viewModel.categoryItems[idx].category)")
}.onMove { indexSet, newOffset in
viewModel.categoryItems.move(fromOffsets: indexSet, toOffset: newOffset)
}
}
}
}
Downside is that you have to access the object via the array as you only get the current index within the loop.