繁体   English   中英

使用 .onDelete -SwiftUI 时索引超出范围

[英]Index Out Of Range When Using .onDelete -SwiftUI

执行 .onDelete 函数时,我得到的索引超出范围。 我已经成功地在我的应用程序的其他地方使用了 onDelete,直接从核心数据中删除了数据。 此版本仅从未存储在核心数据中的列表中删除。

我创建了一些用于测试的临时列表,并且使用这个 .onDelete 是成功的。 成功的测试用例使用的数组中已经有数据并且不需要初始化。 下面代码中使用的数组是在用户登陆此页面时初始化的数组 - 这可能是它失败的原因吗?

这个结构体中有很多代码,但相关部分如下:

@State var recipeStep: [String]

更多代码,最终到达导致问题的 ForEach

            List {
                ForEach(0..<recipeStep.count, id: \.self) { index in
                            HStack {
                                Text(String(stepNumber[index]) + ".").bold()
                                TextField("", text: $recipeStep[index]).multilineTextAlignment(.leading).padding(.leading)
                            }
                }.onDelete { (indexSet) in
                    recipeStep.remove(atOffsets: indexSet)}

关于为什么我得到索引超出范围错误的任何想法?

你用recipeStep in 循环

ForEach(0..<recipeStep.count, id: \.self) { index in

当您同时使用$recipeStep[index]stepNumber[index]

因此recipeStepstepNumber应该具有相同的大小以避免崩溃或更好地将它们stepNumber到 1 个模型中

我能够通过修改我的文本字段以按以下方式工作来使其工作:

EditorView(container: self.$recipeStep, index: index, text: recipeStep[index])

解决方案在这里找到,由 Asperi 发布: https ://stackoverflow.com/a/58911168/12299030

我不得不稍微修改他的解决方案以适合我的 forEach,但总的来说它完美无缺!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM