SwiftUI:使用TextField()时,List,ForEach,索引和.onDelete不起作用-(索引超出范围)

时间:2020-08-28 07:55:13

标签: arrays swift foreach swiftui textfield

我不知道该如何工作-简单的struct数组。 在ForEach中,我有Text(...)的所有东西,包括.onDelete()。 在ForEach中,我得到了TextField(...),然后.onDelete()不再起作用了-Fatal error: Index out of range

struct plan : Identifiable {
    var id = UUID()
    var planName : String = ""
}
struct ContentView: View {
    @State private var pls = [plan(planName: "plan1")]
    
    var body: some View {
        NavigationView  {
            List {
                ForEach (pls.indices, id:\.self) {i in
                    NavigationLink(destination: ItemView(pln: self.$pls[i])) {
                        TextField("", text: self.$pls[i].planName)
//                        Text(self.pls[i].planName)
                    }
                }
                .onDelete { (offset) in
                    for i in offset {
                        let sorted = self.pls.sorted {$0.planName < $1.planName}
                        if let found = self.pls.firstIndex(where: { $0.planName == sorted[i].planName }) {
                            self.pls.remove(at: found)
                        }
                    }
                }
            }
        }
    }
}

0 个答案:

没有答案