【问题标题】:How can I delete an item in a List ? SwiftUI如何删除 List 中的项目? SwiftUI
【发布时间】:2021-01-26 08:53:38
【问题描述】:

我正在尝试使用编辑按钮和函数来编辑列表(由可变字符串组成)。我的代码是:

struct annotationsView: View {
    
    
    @State private var text = ""
    //    annotations
    @State var annotations : [[AnnData]] = [[]]
    
    var body: some View {
        VStack{
            Form{
                HStack{
                    TextField("Add your annotations here", text: $text)
                        .textFieldStyle(RoundedBorderTextFieldStyle())
                    
                    Button("Submit") {
                        annotations[annotations.count - 1].append(AnnData(Anntext: text))
                        self.hideKeyboard()
                        text = ""
                    }
                }
                List{
                    ForEach(annotations.indices, id:\.self){index in
                        
                        ForEach(annotations[index].indices, id:\.self){annotationIndex in
                            
                            Text(annotations[index][annotationIndex].Anntext)
                        }.onDelete(perform: self.deleteItem) //<-- Here
                    }
                }
                
            }
        }
        .background(
            Image("Background")
                .resizable()
                .edgesIgnoringSafeArea(.all)
                .navigationBarTitle(Text("Annotations"), displayMode: .inline)
        )
        .navigationBarItems(trailing: EditButton())
    }
    
    private func deleteItem(at indexSet: IndexSet) {
        annotations.remove(atOffsets: indexSet)
    }
}
struct AnnData : Identifiable{
    
    var id = UUID().uuidString
    var Anntext: String
}

目前,我无法删除单个项目;当我删除一个时,其余的会自动删除。此外,之后我无法在列表中添加一些项目。 你介意解释一下这里出了什么问题吗? 感谢您的帮助!

【问题讨论】:

    标签: list swiftui


    【解决方案1】:

    您需要在循环中删除项目,因为您的数据是一个二维数组。 像这样

    List{
        ForEach(annotations.indices, id:\.self){index in
            
            ForEach(annotations[index].indices, id:\.self){annotationIndex in
                
                Text(annotations[index][annotationIndex].Anntext)
            }
            .onDelete { (indexSet) in
                annotations[index].remove(atOffsets: indexSet)
            }//<-- Here
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-29
      相关资源
      最近更新 更多