当List填充数组时,如何在SwiftUI中获取List中元素的索引?

Ade*_*aer 5 swift swiftui swiftui-list

在我的 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)

             }

        }

        }

    }
Run Code Online (Sandbox Code Playgroud)

问题是,如何获取textItem的索引呢?

例如,如果我想为奇数行和偶数行设置不同的行颜色,或者如果我需要为数字 3 的行实现不同的样式?

在 SwiftUI 中获取列表中项目的索引的最佳方法是什么?

Asp*_*eri 6

这可以通过使用来完成.enumerated。对于您的MenuItem价值观,它将如下

List {
    ForEach(Array(menuItems.enumerated()), id: \.1.id) { (index, textItem) in
        // do with `index` anything needed here
        Text(textItem.text)
    }
}
Run Code Online (Sandbox Code Playgroud)