简体   繁体   中英

How do you use enumerated in a list of structs in ForEach Swiftui?

I wish to utilise the index from the items in ForEach. This is regarding the post I made here where I have now changed the buttonTitles into a list of struct from a dictionary. However I can't seem to do the usual.enumerated() method in ForEach with [struct].

struct ButtonObject: Hashable{
    let id =  UUID()
    var name: String
    var isSelected: Bool

}


class SomeData: ObservableObject{
    @Published var buttonObjects: [ButtonObject] = [ButtonObject(name: "tag1", isSelected: false),
                                                   ButtonObject(name: "tag2", isSelected: false), ButtonObject(name: "tag3", isSelected: false)]
}



struct someData3: View {
    @ObservedObject var someData = SomeData()

    var body: some View {
        VStack{
            ForEach(Array(someData.buttonObjects.enumerated()), id: \.element.id)){ind, object in
                HStack{
                    Text(ind)
                    Text(object.name)
                }
            }




        }

    }
}

Here is fixed part

ForEach(Array(someData.buttonObjects.enumerated()), id: \.element.id) { ind, object in
    HStack{
        Text("\(ind)")
        Text(object.name)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM