问题
In my SwiftUI app, I have a list of items.
I'm using the array of MenuItems to fill in the list
struct MenuItem: Identifiable, Equatable {
var id = UUID()
var text: String
}
struct MenuView: View {
var menuItems = [MenuItem(text:"Text1"),MenuItem(text:"Text2")]
var body: some View {
List {
ForEach(menuItems) {textItem in
Text(textItem.text)
}
}
}
}
The question is, how to get the index of textItem?
For example if I want to have different row colors for odd and even rows, or if I need to implement different styling for the row with number 3?
What is the best way to get the index of the item in the List in SwiftUI?
回答1:
This can be done using using .enumerated
. For your MenuItem
values it will be as follows
List {
ForEach(Array(menuItems.enumerated()), id: \.1.id) { (index, textItem) in
// do with `index` anything needed here
Text(textItem.text)
}
}
来源:https://stackoverflow.com/questions/59863322/how-to-get-the-index-of-the-element-in-the-list-in-swiftui-when-the-list-is-popu