List填充数组时,如何在SwiftUI中获取List中元素的索引?
How to get the index of the element in the List in SwiftUI when the List is populated with the array?
在我的 SwiftUI 应用程序中,我有一个项目列表。
我正在使用 MenuItems 数组来填充列表
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)
}
}
}
}
问题是,如何获取textItem的索引?
例如,如果我想为奇数行和偶数行设置不同的行颜色,或者如果我需要为编号为 3 的行实现不同的样式?
在 SwiftUI 中获取列表中项目索引的最佳方法是什么?
这可以使用 .enumerated
来完成。对于您的 MenuItem
值,它将如下所示
List {
ForEach(Array(menuItems.enumerated()), id: \.1.id) { (index, textItem) in
// do with `index` anything needed here
Text(textItem.text)
}
}
在我的 SwiftUI 应用程序中,我有一个项目列表。
我正在使用 MenuItems 数组来填充列表
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)
}
}
}
}
问题是,如何获取textItem的索引?
例如,如果我想为奇数行和偶数行设置不同的行颜色,或者如果我需要为编号为 3 的行实现不同的样式?
在 SwiftUI 中获取列表中项目索引的最佳方法是什么?
这可以使用 .enumerated
来完成。对于您的 MenuItem
值,它将如下所示
List {
ForEach(Array(menuItems.enumerated()), id: \.1.id) { (index, textItem) in
// do with `index` anything needed here
Text(textItem.text)
}
}