Get index in ForEach in SwiftUI

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

    The advantage of the following approach is that the views in ForEach even change if state values ​​change:

    struct ContentView: View {
        @State private var array = [1, 2, 3]
    
        func doSomething(index: Int) {
            self.array[index] = Int.random(in: 1..<100)
        }
    
        var body: some View {    
            let arrayIndexed = array.enumerated().map({ $0 })
    
            return List(arrayIndexed, id: \.element) { index, item in
    
                Text("\(item)")
                    .padding(20)
                    .background(Color.green)
                    .onTapGesture {
                        self.doSomething(index: index)
                }
            }
        }
    }
    

    ... this can also be used, for example, to remove the last divider in a list:

    struct ContentView: View {
    
        init() {
            UITableView.appearance().separatorStyle = .none
        }
    
        var body: some View {
            let arrayIndexed = [Int](1...5).enumerated().map({ $0 })
    
            return List(arrayIndexed, id: \.element) { index, number in
    
                VStack(alignment: .leading) {
                    Text("\(number)")
    
                    if index < arrayIndexed.count - 1 {
                        Divider()
                    }
                }
            }
        }
    }
    

提交回复
热议问题