我有一个简单的视图:
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
}
}
}
}
}
}