Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
756 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...