SwiftUI ForEach index out of range error when removing row

前端 未结 3 881
日久生厌
日久生厌 2021-01-06 00:39

I have a ForEach block and a Stepper embedded in a List view. The contents of the List view\'s first section is as follow

3条回答
  •  礼貌的吻别
    2021-01-06 01:42

    It works as the following codes.

     struct Node {
    var xString: String = "x"
    var yString: String = "y"
    var x: Int
    var y: Int
     }
    
     struct RecordsNode {
    var nodes : [Node]
     }
    
    struct ContentView: View {
    
    
    
    @State var record: RecordsNode = RecordsNode(nodes: [Node(x: 11, y: 11)])
    
    var body: some View {
    
        Group{
        ForEach(record.nodes.indices, id: \.self) { index in
            HStack {
                TextField("X", text: self.$record.nodes[index].xString)
                Spacer()
                Divider()
                TextField("Y", text: self.$record.nodes[index].yString)
                Spacer()
            }
        }
        Stepper("± node", onIncrement: {
            self.record.nodes.append(Node(x: 0, y: 0))
        }, onDecrement: {
            self.record.nodes.removeLast()
        })}
    
    }}
    

提交回复
热议问题