繁体   English   中英

SwiftUI ForEach 数组索引未呈现

[英]SwiftUI ForEach array indices not rendering

我有一个简单的看法:

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`!

我的 model 是可Identifiable

您可以同时拥有两者,如下所示

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
          }
        }
      }
    }
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM