SwiftUI ForEach 数组索引不呈现

标签 swift swiftui

我有一个简单的看法:

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

最佳答案

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

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

关于SwiftUI ForEach 数组索引不呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62827401/

相关文章:

ios - 完美助手打不开

ios - 如何在 Facebook SDK 中快速共享图像和文本

swiftui - 在 SwiftUI 中重新创建蒙版模糊效果

ios - SwiftUI 中是否有 didSet 的替代方案?

ios - WKWebView 没有加载 url

SwiftUI:TabView 只能在没有绑定(bind)的情况下正常工作(点不会改变)

ios - 输入 Int 的 iOS SwiftUI TextField 缺少占位符

foreach - 如何使用 SwiftUI 在 ScrollView 中选择一个项目?

swift - 在 SwiftUI View 中应用 ClipShape 时,背景颜色从安全区域消失

swift - 运行应用程序时出现错误 "unexpectedly found nil while unwrapping an Optional value"