【问题标题】:SwiftUI ForEach array indices not renderingSwiftUI ForEach 数组索引未呈现
【发布时间】:2020-07-10 04:35:05
【问题描述】:

我有一个简单的看法:

struct SomeView: View {
  @ObservedObject var viewModel: ViewModel()
  var body: some View {
    GeometryReader { fullView in
      ScrollView {
        VStack(spacing: 40) {
          ForEach(self.viewModel.list) { item in
            Text(item.name)
          }
        }
      }
    }
  }
}

这是有效的。但我需要使用索引。我试图改变我的ForEach循环:

ForEach(self.viewModel.list.indices) { index in
  Text(self.viewModel.list[index].name)
}

但这一次ForEach 没有渲染任何东西。但在控制台上写:

ForEach<Range<Int>, Int, ModifiedContent<ModifiedContent<GeometryReader<ModifiedContent<ModifiedContent<ModifiedContent<...>, _FrameLayout>, _TransactionModifier>> count (10) != its initial count (0). `ForEach(_:content:)` should only be used for *constant* data. Instead conform data to `Identifiable` or use `ForEach(_:id:content:)` and provide an explicit `id`!

我的模特是Identifiable

【问题讨论】:

    标签: swift swiftui


    【解决方案1】:

    你可以同时拥有,如下所示

    struct SomeView: View {
      @ObservedObject var viewModel: ViewModel()
      var body: some View {
        GeometryReader { fullView in
          ScrollView {
            VStack(spacing: 40) {
              ForEach(Array(self.viewModel.list.enumerated()), id: \.1) { index, item in
                Text(item.name)
                // ... use index here as needed
              }
            }
          }
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-11
      • 1970-01-01
      • 2020-09-18
      • 2020-05-09
      • 1970-01-01
      • 1970-01-01
      • 2019-12-06
      • 1970-01-01
      相关资源
      最近更新 更多