Get index in ForEach in SwiftUI

前端 未结 6 1894
执笔经年
执笔经年 2020-12-24 05:01

I have an array and I want to iterate through it initialize views based on array value, and want to perform action based on array item index

When I iterate through o

6条回答
  •  暖寄归人
    2020-12-24 05:49

    I created a dedicated View for this purpose based on the awesome Stone's solution:

    struct EnumeratedForEach: View {
        let data: [ItemType]
        let content: (Int, ItemType) -> ContentView
        
        init(_ data: [ItemType], @ViewBuilder content: @escaping (Int, ItemType) -> ContentView) {
            self.data = data
            self.content = content
        }
        
        var body: some View {
            ForEach(Array(self.data.enumerated()), id: \.offset) { idx, item in
                self.content(idx, item)
            }
        }
    }
    

    Now you can use it like this:

    EnumeratedForEach(items) { idx, item in
        ...
    }
    

提交回复
热议问题