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

試著忘記壹切 提交于 2021-01-28 14:02:09

问题


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




        }

    }
}

回答1:


Here is fixed part

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


来源:https://stackoverflow.com/questions/62384053/how-do-you-use-enumerated-in-a-list-of-structs-in-foreach-swiftui

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