提问者:小点点

在SwiftUI中用数组填充列表时,如何获取列表中元素的索引?


在我的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中获取列表中项目的索引的最好方法是什么?


共1个答案

匿名用户

这可以使用. enumerted来完成。对于您的Menu项目值,如下所示

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