这是我在开发SwiftUI应用程序时遇到的错误的概念证明,该程序需要在视图之间同步数据,这就是我使用ObservedObject和Binding的原因。
这是应用程序的代码
import SwiftUI
struct Person: Hashable{
var id: String
var name: String
}
class People: ObservableObject{
@Published var items: [Person]
init (){
self.items = [
Person(id: "1", name: "Juan"),
Person(id: "2", name: "Javier"),
Person(id: "3", name: "Alvaro")
].sorted(by:{$0.name < $1.name})
}
}
struct ContentView: View {
@ObservedObject var people = People()
var body: some View {
NavigationView{
List{
ForEach(Array(people.items.enumerated()), id: \.1.id) { (index, _) in
NavigationLink(destination: PersonDetailView(person:Binding(
get: { self.people.items[index] },
set: { self.people.items[index] = $0 }))){
PersonListRowView(person: self.$people.items[index])
}
}
}
.navigationBarTitle("People", displayMode: .large)
.navigationBarItems(trailing:
Button(
action: {
self.people.items.removeLast()
},
label: { Image(systemName: "trash")
.frame(width: 30, height: 30)
}
)
)
}
}
}
struct PersonListRowView: View {
@Binding var person: Person
var body: some View {
Text("\(person.name)")
}
}
struct PersonDetailView: View {
@Binding var person: Person
var body: some View {
VStack{
Text("My name is \(self.person.name)")
Button("Change name"){
self.person.name = "Pepe"
}
}
}
}
当我在列表中删除一个人(单击垃圾箱图标)时,出现问题,我收到一个错误,应用崩溃了。
在玩了很多游戏并且看了很多文章之后,我发现这个问题与Using ForEach loop with Binding causes index out of range when array shrinks (SwiftUI)十分相似,但是我使用了NavigationLink,正是这个原因导致了问题。如果您对NavigationLink进行注释,则在删除项目时应用程序会平稳运行
有什么线索,怎么解决?