【发布时间】:2020-11-04 15:20:25
【问题描述】:
我的问题是:我有一些包含一些项目的简单数组。我想使用带有ForEach 和.indices() 的ForEach 显示带有这些项目的List。
(这是因为我在List 中处理Toggle 的实际问题,对于isOn 绑定,我需要索引来处理绑定到EnvironmentObject 的模型)。所以循环数组items的解决方案对于我的问题是不可能的。
简化的起点如下所示:
struct ContentView: View {
@State var items = ["Item1", "Item2", "Item3"]
var body: some View {
List {
ForEach(items.indices) {index in
Text(self.items[index])
}.onDelete(perform: deleteItem)
}
}
func deleteItem(indexSet: IndexSet) {
self.items.remove(atOffsets: indexSet)
}
}
如果我现在尝试滑动删除一行,我会收到以下错误消息:
Thread 1: Fatal error: Index out of range
调试闭包内的index 值,我可以看到items-array 的索引没有更新。例如:如果我用"Item 1" 删除第一行并在删除该行后检查index 的值,它将返回2 而不是0(这是预期的数组的第一个索引)。为什么会这样?我该如何解决这个问题?
感谢您的帮助!
【问题讨论】: