我试图了解 SwiftUI 绑定(bind)。在这里,我在 View 中显示一个数组并将值绑定(bind)到第二个 View 。在第二个 View 中,我从数组中删除数据。
但是我得到以下信息,
Fatal error: Index out of range
我没有收到
self.person.notes.remove(at: self.index)
的错误实际上,这实际上是在删除数组中的注释。使用ForEach
时必须在第一 View 由于数组已被修改,现在它超出了范围。但我不确定如何解决这个问题?肯定是Binding
应该解决这个问题。查看 1
ForEach(self.person.notes.indices, id:\.self) { index in
NoteView(person: self.$person, room: self.$home.notes[index], index: index)
}
查看 2 @Binding var person: Person
@Binding var note: Note
var index: Int
if self.index > 0 {
Button(action: {
self.person.notes.remove(at: self.index)
}) {
Text("Remove")
}
}
知道这应该如何在 SwiftUI 中工作吗?
最佳答案
使用预先给定的索引删除总是有风险的。数据在后台更改的可能性等。在您尝试删除项目时获取索引以确保拥有正确的索引。以防数据在其他地方发生变化。
这应该可以帮助您理解:
struct ContentView: View {
@State var myData: Array<String> = ["first", "second", "third"]
var body: some View {
ForEach(self.myData, id: \.self) { data in
SecondView(myData: self.$myData, data: data)
}
}
}
struct SecondView: View {
@Binding var myData: Array<String>
// the data that is being tied to the view
var data: String
var body: some View {
Button(action: {
// calculate the index at the time of removal
if let index = self.myData.firstIndex(of: self.data) {
self.myData.remove(at: index)
}
}) {
Rectangle().foregroundColor(Color.red).frame(width: 100, height: 100).overlay(Text("Button \(self.data)"))
}
}
}
产生这个:正如您所提到的,您的错误在于第一个 View 。这很可能是因为您正在使用索引数量构建 ForEach。当您删除一个时,ForEach 会遇到错误,因为它失去了对该项目的“跟踪”,并且具有 ForEach 提供的索引的项目不再存在。
试试这个:
ForEach(self.person.notes, id:\.self) { note in
// Remove the index and calculate it on the second view as shown above. This then should solve the problem
NoteView(person: self.$person, room: self.$home.notes)
}
关于ios - 从数组中删除 - fatal error : Index out of range - SwiftUI Binding,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62780575/