带有ForEach的SwiftUI列表可在一个VStack中工作,但不能在第二个VStack中工作

时间:2020-06-17 00:30:51

标签: swiftui swiftui-list

我完全不知道为什么我要在ForEach中创建(带有SwiftUI的列表)的行为。我有一个ObservedObject,我在检查员中验证了我所期望的数据。在第一个VStack中,我可以使用ForEach创建列表,并且输出就很好。在第二个VStack中,没有任何数据输出。

struct WorkoutPreview: View {
  @Environment(\.managedObjectContext) var managedObjectContext
  @ObservedObject var workoutSessionExercises: WorkoutSessionExercises

  var body: some View {
    NavigationView {
      VStack {
        Text("Welcome to your workout! Below are the exercises and bands you've selected for each.")
          .padding()
        Text("We found \(workoutSessionExercises.workoutExercises.count) workouts.")
          .padding()

        // This List (with ForEach) works fine and produces output.
        List {
          ForEach(0..<workoutSessionExercises.workoutExercises.count) { index in
            Text(self.workoutSessionExercises.workoutExercises[index].exerciseName)
          }
        }
      }

      // The exact same List (with ForEach) in this VStack produces no results.
      VStack {
        List {
          ForEach(0..<workoutSessionExercises.workoutExercises.count) { index in
            Text(self.workoutSessionExercises.workoutExercises[index].exerciseName)
          }
        }
      }

      Spacer()
    }
  }
}

1 个答案:

答案 0 :(得分:0)

问题是您有2个VStack,它们在View中彼此都不比另一个低,因此您看不到第二个列表。 要解决您的问题,请将您的VStack包裹在另一个VStack中,例如:

var body: some View {
    NavigationView {
        VStack {   //  <------
            VStack {
                Text("Welcome to your workout! Below are the exercises and bands you've selected for each.").padding()
                Text("We found \(workoutSessionExercises.workoutExercises.count) workouts.").padding()
                // This List (with ForEach) works fine and produces output.
                List {
                    ForEach(0..<workoutSessionExercises.workoutExercises.count) { index in
                        Text(self.workoutSessionExercises.workoutExercises[index].exerciseName)
                    }
                }
            }
            // The exact same List (with ForEach) in this VStack produces no results.
            VStack {
                List {
                    ForEach(0..<workoutSessionExercises.workoutExercises.count) { index in
                        Text(self.workoutSessionExercises.workoutExercises[index].exerciseName)
                    }
                }
            }
            Spacer()
        }         //  <------
    }
}