gpt4 book ai didi

SwiftUI ForEach 数组索引不呈现

转载 作者:行者123 更新时间:2023-12-04 09:31:20 27 4
gpt4 key购买 nike

我有一个简单的看法:

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com