当我尝试通过导航链接删除列表视图中的一行时超出索引

时间:2020-03-05 14:23:59

标签: swiftui swiftui-list swiftui-navigationlink

    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部件,则可以删除任何行。 我该如何解决? 谢谢。

1 个答案:

答案 0 :(得分: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())
    }
}