How to get the index of the element in the List in SwiftUI when the List is populated with the array?

本秂侑毒 提交于 2020-07-13 15:29:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!