在foreach循环SwiftUI中为每次迭代设置变量

n53p2ov0  于 2023-02-18  发布在  Swift
关注(0)|答案(1)|浏览(102)

我有一个嵌套的foreach循环,我想修改嵌套循环中每个元素的数据,如下所示:

struct trainingView: View {

   @ObservedObject var workout: Workout

   @State private var reps: Int = 0

    
   var body: some View {
       ForEach(workout.exercises, id: \.self) { exercise in

            Text(exercise.nameOfExercise)

            ForEach(0..<exercise.amountOfSets, id: \.self) { Set in

                 Text("\(Set+1) Set")
                 Text(reps)
                 Stepper("Reps", value: $reps , in: 0...30)

                 }
              }
           }
         }

我想变量代表是独立的变化,在另一个元素步进器。如果你需要更好的例子的代码只是问。
这是不起作用的,因为一个变化会影响所有元素。我也尝试过在嵌套循环中创建一个@State对象,但这也不起作用。我也尝试过创建一个数组来存储数据,但这似乎很复杂,因为数组的大小可能会在不同的时间发生变化。我尝试过在这里搜索信息,但没有找到任何人回答。我刚接触swiftUI,需要帮助。

oprakyz7

oprakyz71#

您示例中的Stepper接受一个到数值的绑定。如果您创建了一个数组的数组,则可以通过索引访问其中的每一行和元素来创建绑定,例如:

struct Exercise: Identifiable, Equatable, Hashable {
    let id = UUID()
    let name: String
    var sets: [Set]
}

struct Set: Identifiable, Equatable, Hashable {
    let id = UUID()
    let name: String
    let requiredReps: Int = 10
    var reps: Int = 0
}

class Workout: ObservableObject {

    @Published var exercises: [Exercise]

    init(exercises: [Exercise]) {
        self.exercises = exercises
    }    
}

struct ContentView: View {

    @StateObject var workout = Workout(exercises: [
        Exercise(name: "Squats", sets: [Set(name: "Set 1"), Set(name: "Set 2"), Set(name: "Set 3")]),
        Exercise(name: "Lunges", sets: [Set(name: "Set 1"), Set(name: "Set 2"), Set(name: "Set 3")]),
        Exercise(name: "Burpees", sets: [Set(name: "Set 1"), Set(name: "Set 2"), Set(name: "Set 3")])
    ])
    
    var body: some View {
        List {
            ForEach(workout.exercises) { exercise in
                Section(exercise.name) {
                    let rowIndex = workout.exercises.firstIndex(of: exercise)!
                    HStack {
                        ForEach(exercise.sets) { set in
                            let objectIndex = exercise.sets.firstIndex(of: set)!
                            VStack {
                                Text(set.name + ": ") + Text(set.reps, format: .number) + Text("/") + Text(set.requiredReps, format: .number)
                                
                                Stepper("Reps", value: $workout.exercises[rowIndex].sets[objectIndex].reps, in: 0...set.requiredReps)
                                    .labelsHidden()
                            }
                        }
                    }
                }
            }
            .padding()
        }
    }
}

相关问题