Get index in ForEach in SwiftUI

前端 未结 6 1888
执笔经年
执笔经年 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:50

    This works for me:

    Using Range and Count

    struct ContentView: View {
        @State private var array = [1, 1, 2]
    
        func doSomething(index: Int) {
            self.array = [1, 2, 3]
        }
        
        var body: some View {
            ForEach(0..

    Using Array's Indices

    The indices property is a range of numbers.

    struct ContentView: View {
        @State private var array = [1, 1, 2]
    
        func doSomething(index: Int) {
            self.array = [1, 2, 3]
        }
        
        var body: some View {
            ForEach(array.indices) { i in
              Text("\(self.array[i])")
                .onTapGesture { self.doSomething(index: i) }
            }
        }
    }
    

提交回复
热议问题