带有 .indices() 的 SwiftUI ForEach 在 onDelete 后不会更新 [英] SwiftUI ForEach with .indices() does not update after onDelete

查看:31
本文介绍了带有 .indices() 的 SwiftUI ForEach 在 onDelete 后不会更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是:我有一些带有一些项目的简单数组.我想使用带有 .indices()ForEach 来显示带有这些项目的 List.(这是因为我的实际问题是在 List 中使用 Toggle 处理,而对于 isOn 绑定,我需要索引来解决绑定的模型到 EnvironmentObject).因此,循环遍历数组 items 的解决方案对于我的问题是不可能的.

my problem is: I have simple array with some Items. I want to display a List with these items using a ForEach with .indices(). (This is because my actual problem handles with Toggle in a List and for the isOn binding I need the index to address a model that is bound to an EnvironmentObject). So the solution to loop over the array items is no possible solution for my problem.

简化的起点如下所示:

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)
    }
}

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

If I now try to swipe-delete a row, I get this error message:

Thread 1: Fatal error: Index out of range

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

Debugging the index value inside the closure, I can see, that the indices of the items-array does not update. For example: If I delete the first row with "Item 1" and inspect the value of index after deleting the row it returns 2 instead of 0 (which is the expected first index of the array). Why is this and how can I fix this problem?

感谢您的帮助!

推荐答案

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

Just use dynamic content ForEach constructor (_ data: .., id: ...)

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

这篇关于带有 .indices() 的 SwiftUI ForEach 在 onDelete 后不会更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆