0
    struct PocketListView: View {
    @EnvironmentObject var pocket:Pocket
    var body: some View {
        NavigationView{
            List{
                ForEach(self.pocket.moneyList.indices,id: \.self){index in
                    NavigationLink(destination:  MoneyView(money: self.$pocket.moneyList[index])){
                        MoneyNoTouchView(money: self.$pocket.moneyList[index])
                    }


                }.onDelete(perform: {index in
                    self.pocket.moneyList.remove(at: index.first!)
                })
                Spacer()
                HStack{
                    Image(systemName: "plus")
                        .onTapGesture {
                            self.pocket.add()
                    }
                }

            }
        }

    }
}


    struct Money {
    var id = UUID()
    var value = 0
}

    class Pocket: ObservableObject,Identifiable {
        @Published var id = UUID()
        @Published var moneyList = [Money]()

        func add() {
            self.moneyList.append(Money())
            print(moneyList.count)
        }
    }

当我尝试删除任何行时,应用程序将崩溃并且我得到这个“致命错误:索引超出范围”。如果我在我的代码中删除 NavigationLink 部分,则可以删除任何行。我该如何解决这个问题?谢谢你。

4

1 回答 1

1

谢谢你的代码。

我不得不更改/扩展一些东西,因为仍然缺少一些代码来编译您的示例,但我的代码有效....也许它可以帮助您

import SwiftUI


struct A : View {

    var body: some View {
        Text("a")
    }
}

struct ContentView: View {
    @EnvironmentObject var pocket:Pocket
    var body: some View {
        NavigationView{
            List{
                ForEach(self.pocket.moneyList.indices,id: \.self) { index in
                    NavigationLink(destination: A()){
                        Text("\(self.pocket.moneyList[index].value)")
                    }


                }.onDelete(perform: {index in
                    self.pocket.moneyList.remove(at: index.first!)
                })
                Spacer()
                HStack{
                    Image(systemName: "plus")
                        .onTapGesture {
                            self.pocket.add()
                    }
                }
            }
        }
    }
}


struct Money {
    var id = UUID()
    var value = 0
}

class Pocket: ObservableObject,Identifiable {
    @Published var id = UUID()
    @Published var moneyList = [Money]()

    func add() {
        self.moneyList.append(Money())
        print(moneyList.count)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {

        var pocket = Pocket()
        pocket.moneyList.append(Money(id: UUID(), value: 1))
        pocket.moneyList.append(Money(id: UUID(), value: 2))
        pocket.moneyList.append(Money(id: UUID(), value: 3))

        return ContentView().environmentObject(Pocket())
    }
}
于 2020-03-05T16:25:04.860 回答