带有 .indices() 的 SwiftUI ForEach 在 onDelete 后不更新
SwiftUI ForEach with .indices() does not update after onDelete
我的问题是:我有一些简单的数组。我想使用带有 .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
数组的索引不会更新。例如:如果我用 "Item 1"
删除第一行并在删除行后检查 index
的值 returns 2
而不是 0
(这是数组的预期第一个索引)。为什么会这样,我该如何解决这个问题?
感谢您的帮助!
只需使用动态内容ForEach
构造函数(_ data: .., id: ...)
ForEach(items.indices, id: \.self) {index in // << here !!
Text(self.items[index])
}.onDelete(perform: deleteItem)
我的问题是:我有一些简单的数组。我想使用带有 .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
数组的索引不会更新。例如:如果我用 "Item 1"
删除第一行并在删除行后检查 index
的值 returns 2
而不是 0
(这是数组的预期第一个索引)。为什么会这样,我该如何解决这个问题?
感谢您的帮助!
只需使用动态内容ForEach
构造函数(_ data: .., id: ...)
ForEach(items.indices, id: \.self) {index in // << here !!
Text(self.items[index])
}.onDelete(perform: deleteItem)