带有 .indices() 的 SwiftUI ForEach 在 onDelete 后不会更新

5 indices swiftui

我的问题是:我有一些项目的简单数组。我想List使用ForEachwith显示这些项目.indices()。(这是因为我的实际问题是Toggle在 a 中处理的List,对于isOn绑定,我需要索引来处理绑定到 a 的模型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)
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我现在尝试滑动删除一行,则会收到以下错误消息:

Thread 1: Fatal error: Index out of range
Run Code Online (Sandbox Code Playgroud)

调试index闭包内的值,我可以看到items-array的索引没有更新。例如:如果我删除第一行"Item 1"并检查index删除行后的值,它将返回2而不是0(这是数组的预期第一个索引)。这是为什么,我该如何解决这个问题?

谢谢你的帮助!

Asp*_*eri 6

只需使用动态内容ForEach构造函数(_ data: .., id: ...)

ForEach(items.indices, id: \.self) {index in   // << here !!
    Text(self.items[index])
}.onDelete(perform: deleteItem)
Run Code Online (Sandbox Code Playgroud)