Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
807 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...