I have an array of five different types of fruit names. I have a list which displays this array. When I .onDelete a fruit, I want to obtain the integer reflecting the row in the list which that certain fruit is on (right now I'm not concerned with actually deleting the fruit from the list). So for example, banana would be on row 1, apple would be on row 2, etc. Is there a way to obtain this integer using some function of IndexSet?
Here's the code:
var fruits:[String] = ["banana", "apple", "grape", "pear", "kiwi"]
List {
ForEach(fruits) {fruit in
Text(fruit)
}
.onDelete(perform: obtainingTheRowNumber)
}
func obtainingTheRowNumber(indexSet: IndexSet) -> Int {
//I want this function to return the row number of the object being deleted but I'm not sure how.
}
I've tried looking into the documentation around IndexSet but I couldn't find anything and I feel like I'm missing something super simple.
CodePudding user response:
You can use this below code...
func obtainingTheRowNumber(indexSet: IndexSet){
let index = indexSet[indexSet.startIndex] // get index from here
print(index)
}
CodePudding user response:
struct ContentView: View {
var fruits:[String] = ["banana", "apple", "grape", "pear", "kiwi"]
var body: some View {
List {
ForEach(fruits, id:\.self) {fruit in
Text(fruit)
}
.onDelete(perform: obtainingTheRowNumber)
}
}
func obtainingTheRowNumber(indexSet: IndexSet) {
for index in indexSet {
print(index 1)
}
}
}